I came across a problem in this link https://leetcode.com/problems/contains-duplicate/. There is an input array of integers. Find out if there any repeating integers, then return true else false.
How can I optimize this code?
Can I improve the logic further?
In my code below,there is an if condition if(hPtr && hPtr->key == *(nums+i))
. I am using the array elements as keys. If so, each key can't be unique if the same element is repeated twice right? So can I modify the if condition as if(hPtr->key == *(nums + i))?
If any other mistakes, please feel free to point out.
There is already a hashtable library available in C http://troydhanson.github.io/uthash/userguide.html and wrote the below code.
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;
}