Simple C solution in 4ms


  • 0
    S

    The idea is to walk two pointers inward from the ends of the
    array, at each point looking at their sum. If it's exactly k, then we're done. If it exceeds k,
    then any sum using the larger element is too large, so we walk that pointer inwards. If
    it's less than k, then any sum using the lower element is too small, so we walk that
    pointer inwards.

    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
            *returnSize = 2;
            int i=0;
            int j=numbersSize-1;
            int c;
            int sum = 0;
            int* out = malloc(sizeof(int)*2);
            while(target!=numbers[i]+numbers[j])
            {
                sum = numbers[i]+numbers[j];
                if(sum>target)
                {
                    j--;
                }else
                {
                    i++;
                }
            }
            out[0]=i+1;
            out[1]=j+1;
            return out;
    }
    

  • 2
    N

    Wouldn't the array need to be sorted for this method?


  • 0
    T

    in your solution , numbers should be sorted before


Log in to reply
 

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