C-我在Leetcode No 1(两个总和)上遇到了一个运行时错误



我将哈希表与线性探测使用来解决此问题。然后我在Visual Studio上测试了我的代码,并获得了正确的解决方案。这是代码:

#define HTCAPACITY 50000
int hash(int key) {
    return key % HTCAPACITY;
}
void htInsert(int *keys, int *values, int key, int value) {
    int index = hash(key);
    while(values[index] >= 0)
        index = (index + 1) % HTCAPACITY;
    keys[index] = key;
    values[index] = value;
}
int htSearch(int *keys, int *values, int key) {
    int index = hash(key);
    while(values[index] >= 0) {
        if(keys[index] == key)
            return values[index];
        index = (index + 1) % HTCAPACITY;
    }
    return -1;
}

int* twoSum(int* nums, int numsSize, int target) {
    int keys[HTCAPACITY] = {0};
    int values[HTCAPACITY];
    memset(values, -1, sizeof(int)*HTCAPACITY);
    int i;
    int value = -1;
    int *indices = (int *)malloc(sizeof(int)*2);
    int complement;
    for(i=0; i<numsSize; i++) {
        complement = target - nums[i];
        if((value = htSearch(keys, values, complement)) != -1) {
            indices[0] = value;
            indices[1] = i;
            return indices;
        } else {
            htInsert(keys, values, nums[i], i);
        }
    }
    return NULL;
}

和错误描述在这里:(对不起,我无法直接复制消息)错误描述

和leetcode告诉最后执行的输入是[0、4、3、0]和0

您尚未包含测试程序或功能的确切输入。但是,我危害了一个猜测,补充结果是负面的。

您的错误可能是您的哈希功能。您将%(剩余操作员)用于哈希值。负数的%返回负数。请参阅Modulo操作的负数

我怀疑您会得到负键值,这会导致值和键在分配之前引用内存。

最新更新