Code working for small test cases but showing Wrong Answer for larger test cases on Leetcode


  • 0
    S
    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
     
    int* twoSum(int* nums, int numsSize, int target) {
        int *result = (int *)malloc(2* sizeof(int));
        int i=0, temp, min = nums[0], max = nums[0];
        for(i=1; i<numsSize; i++){
            max = max< nums[i]? nums[i]: max;
            min = min> nums[i]? nums[i]: min;
        }
        int n = max -min +1;
        int *hash= (int *)malloc(n* sizeof(int));
        memset(hash, -1, n* sizeof(int));
        for(i=0; i<numsSize; i++)
            hash[nums[i]% n] = i;
        i=0;
        while(i< numsSize){
            temp = nums[i];
            //Fatal Case:: target - temp = -7 && temp =5
            if((target- temp) %n >=0)
                if(hash[(target - temp)% n] !=i && hash[(target - temp)%n] != -1){
                    result[0] = i+1;
                    result[1] = hash[(target - temp)%n]+1;
                    return result;
                }
        i++;
        }
        return 0;
    }

Log in to reply
 

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