Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. struct hash {
  2. int key;
  3. int value;
  4. UT_hash_handle hh;
  5. };
  6.  
  7. struct hash *hashtable = NULL;
  8.  
  9. void addToHash(int key, int value)
  10. {
  11. struct hash *map;
  12. //I am using the array elements as hash keys
  13. HASH_FIND_INT(hashtable, &key, map);
  14.  
  15. if(map == NULL)
  16. {
  17. map = (struct hash*)malloc(sizeof(struct hash));
  18. map->key = key;
  19. HASH_ADD_INT(hashtable, key, map);
  20. }
  21. map->value = value;
  22. }
  23.  
  24.  
  25. struct hash *findInHash(int key)
  26. {
  27. struct hash *h;
  28. HASH_FIND_INT(hashtable, &key, h);
  29. return h;
  30. }
  31.  
  32. bool containsDuplicate(int* nums, int numsSize) {
  33.  
  34. struct hash *hPtr;
  35. int target = 0;
  36. hashtable = NULL;
  37. if((numsSize <= 1) || (nums == 0)) return false;
  38.  
  39. int i, index1 = 0;
  40.  
  41. for(i = 0; i < numsSize; i++)
  42. {
  43. /*The below statement will look if the key is already present in the
  44. hashtable*/
  45. hPtr = findInHash(*(nums + i) - target);
  46. /*If the key is found already, then it look for the value of that
  47. key. If the value and the current array element is same, then a
  48. duplicate exist*/
  49. if(hPtr && hPtr->key == *(nums+i))
  50. return true;
  51. addToHash(*(nums + i), i);
  52. }
  53. struct hash *temp;
  54. HASH_ITER(hh, hashtable, hPtr, temp) {free(hPtr);}
  55. return false;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement