Accepted C code 5ms


  • 1
    D

    Heres's my accepted 5ms solution

    int* twoSum(int* nums, int numsSize, int target) 
    {
     int* result = malloc(2*sizeof(int));
     result[0] = result[1] = 0;
     for(int i = numsSize -1 ; i > -1; i--)   
     {
        if(nums[i] <= target || target < 0)
        {
            for(int j = 0 ; j< numsSize; j++)   
            {
                if(i ^ j)
                {
                    int temp = nums[i] + nums[j];
                    if(temp == target)
                    {
                        result[0] = i > j ? j + 1 : i + 1;
                        result[1] = j > i ? j + 1 : i + 1;
    
                       return result;
                    }
                }
            }
        }
     }
     return result;
    }

  • 0
    B

    why needs the judgement "nums[i] <= target || target < 0"?


  • 0
    A

    Can the input array be identical with two elements? such as arr={2, 3, 5, 5, 9}, and my target will be 7, so the output will be [1, 3] or [1, 4]? with your solution, the output is [1, 4], is there any possibility the answer is [1,3]


  • 0
    T

    Why "if(i ^ j)" not "if (i != j)" ?


  • 0
    M

    Its given in the problem statement that there will be only one solution in the input


  • 0
    M

    Its not mentioned that the array is sorted. So the performance will degrade if both the indices lie in beginning of the array.


  • 0
    S

    Isnt your solution using O(n^2) time ? Wouldn't it be better to sort firt so that it o(nlogn) time.


  • 0
    C

    @danny10 your codes runtime is o(n^2)? whats the best situation?


Log in to reply
 

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