Accepted C solution using uthash - beats 91.41%


  • 0
    S
    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */    
    
    struct hash_entry 
    {
        int id;            /* we'll use this field as the key */
        int index;
        UT_hash_handle hh; /* makes this structure hashable */
    };
    
    void add_user(int user_id, int index, struct hash_entry **users) 
    {
        struct hash_entry *s;
        HASH_FIND_INT(*users, &user_id, s);  /* id already in the hash? */
        if (s==NULL) {
          s = (struct hash_entry*)malloc(sizeof(struct hash_entry));
          s->id = user_id;
          s->index = index;
          HASH_ADD_INT(*users, id, s );  /* id: name of key field */
        }
    }
    struct hash_entry* find_user(int user_id, struct hash_entry **users)
    {
        struct hash_entry* s;
        HASH_FIND_INT(*users, &user_id, s);
        return s;
    }
    
    int* twoSum(int* nums, int numsSize, int target) {
        struct hash_entry *users = NULL;    
        int* ret = (int*)malloc(sizeof(int) * 2);
        struct hash_entry* s;
        
        for(int i = 0; i < numsSize; ++i)
        {
            s = find_user(target - nums[i], &users);
            if(s == NULL)
                add_user(nums[i],i, &users);
            else
            {
                ret[0] = s->index;
                ret[1] = i;
                return ret;
            }
        }
        return ret;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.