Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement