【发布时间】:2019-06-01 06:20:07
【问题描述】:
我在此链接https://leetcode.com/problems/contains-duplicate/ 中遇到了问题。有一个整数输入数组。找出是否有任何重复的整数,然后返回 true 否则返回 false。
如何优化此代码?
我可以进一步改进逻辑吗?
在我下面的代码中,有一个 if 条件 if(hPtr && hPtr->key == *(nums+i))。我使用数组元素作为键。如果是这样,如果相同的元素重复两次,每个键就不能是唯一的吗?那么我可以将if条件修改为if(hPtr->key == *(nums + i))?
如有其他错误,欢迎指出。
C http://troydhanson.github.io/uthash/userguide.html 中已经有一个可用的哈希表库,并编写了以下代码。
struct hash {
int key;
int value;
UT_hash_handle hh;
};
struct hash *hashtable = NULL;
void addToHash(int key, int value)
{
struct hash *map;
//I am using the array elements as hash keys
HASH_FIND_INT(hashtable, &key, map);
if(map == NULL)
{
map = (struct hash*)malloc(sizeof(struct hash));
map->key = key;
HASH_ADD_INT(hashtable, key, map);
}
map->value = value;
}
struct hash *findInHash(int key)
{
struct hash *h;
HASH_FIND_INT(hashtable, &key, h);
return h;
}
bool containsDuplicate(int* nums, int numsSize) {
struct hash *hPtr;
int target = 0;
hashtable = NULL;
if((numsSize <= 1) || (nums == 0)) return false;
int i, index1 = 0;
for(i = 0; i < numsSize; i++)
{
/*The below statement will look if the key is already present in
the hashtable*/
hPtr = findInHash(*(nums + i) - target);
/*If the key is found already, then it look for the value of that
key. If the value and the current array element is same, then a
duplicate exist*/
if(hPtr && hPtr->key == *(nums+i))
return true;
addToHash(*(nums + i), i);
}
struct hash *temp;
HASH_ITER(hh, hashtable, hPtr, temp) {free(hPtr);}
return false;
}
【问题讨论】:
-
你可以选择你的语言,我想用C来解决。
-
如果你想在 C 中解决这个问题,那很好,但你必须进行某种单元测试,否则你会在没有任何形式的代码验证的情况下磕磕绊绊。正确完成的单元测试将很快验证您的代码是否正确,并将为您节省大量猜测、思考和调试的时间。
-
就性能而言,即使使用
time,也可以轻松地对这段代码进行基准测试,运行长度不同。 -
很抱歉问这个问题,但我还没有进行任何单元测试。有什么要开始的指针吗?
-
搜索“C单元测试框架”,有plethora of options。