Accepted C Program run in 8ms


  • 0
    X
        /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* twoSum(int* nums, int numsSize, int target) {
        int *result = (int*) malloc(sizeof(int) * 2);
        int hashSize = 100;
        int *hashtable = (int*) malloc(sizeof(int) * numsSize * hashSize);
        memset(hashtable,-1,numsSize * sizeof(int) * hashSize);
        int i;
        int index = 0;
        int mapkey = 0;
    	//create hashtable
        for(i = 0; i < numsSize; i ++)
        {
            mapkey = nums[i] % (numsSize * hashSize);
    		if(mapkey < 0)
    			mapkey += (numsSize * hashSize);
            while(hashtable [mapkey] != -1)
            {
                mapkey += numsSize ;
                mapkey %= (numsSize * hashSize);
            }
            hashtable[mapkey % (numsSize * hashSize)] = i;
        }
        //find values 
        for(i = 0; i < numsSize ; i ++)
        {
            mapkey = (target - nums[i]) % (numsSize * hashSize);
    		if(mapkey < 0)
    			mapkey += (numsSize * hashSize);
            while(hashtable[mapkey] != -1 && nums[hashtable[mapkey]] != (target - nums[i]))
            {
                mapkey += numsSize;
                mapkey %= (numsSize * hashSize);
            }
            if(hashtable[mapkey] == -1 )
                continue;
            index = hashtable[mapkey];
            if(index == i)
                continue;
            result[0] = i < index? (i+1) : (index+1);
            result[1] = i > index? (i+1) : (index+1);
            free(hashtable);
            hashtable = NULL;
            return result;
        }
    }

Log in to reply
 

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