Key uniqueness

31 views
Skip to first unread message

Hariprasad Govindarajan

unread,
May 31, 2019, 5:13:33 PM5/31/19
to uthash
I came across a problem in this link 
There is an input array of integers. I need to find out if there any repeating integers, then return true else false.
I tried using uthash and my code below works and got accepted. But I got few questions and someone please clarify me:
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;
       
}



In my code above,there is an if conditionif(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.

Thanks
G Hariprasad


Reply all
Reply to author
Forward
0 new messages