# [Leetcode 167]Two Sum II — Input array is sorted

Description:

Given an array of integers `numbers` that is already sorted in non-decreasing order, find two numbers such that they add up to a specific `target` number.

Return the indices of the two numbers (1-indexed) as an integer array `answer` of size `2`, where `1 <= answer[0] < answer[1] <= numbers.length`.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Example 1:

`Input: numbers = [2,7,11,15], target = 9Output: [1,2]Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.`

Example 2:

`Input: numbers = [2,3,4], target = 6Output: [1,3]`

Example 3:

`Input: numbers = [-1,0], target = -1Output: [1,2]`

Constraints:

• `2 <= numbers.length <= 3 * 104`
• `-1000 <= numbers[i] <= 1000`
• `numbers` is sorted in non-decreasing order.
• `-1000 <= target <= 1000`
• The tests are generated such that there is exactly one solution.

C code solution 1:

`int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){    int * ans = (int*)malloc(sizeof(int)*2);    *returnSize = 2;    int i = 0, j = numbersSize-1;    while(i < j)    {        if(numbers[i] + numbers[j] == target)        {            ans[0] = i+1;            ans[1] = j+1;            return ans;        }        else if(numbers[i] + numbers[j] > target)        {            j--;        }        else        {            i++;        }    }    return NULL;}`

Explanation:

C code solution 2 (using hash):

`int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){    *returnSize = 2; //return array must be 2    int* res = (int*)calloc(2, sizeof(int));    int hash[4001] = {0}; // idex: need, value: index in numbers + 1    for(int i=0; i<numbersSize; i++){        int need = target - numbers[i];        if(hash[need+1000] != 0){            res[0] = hash[need+1000]; // +1 already            res[1] = i + 1; // i has not yet +1            printf("%d %d", res[0], res[1]);            break;        }else{            hash[numbers[i]+1000] = i + 1;        }    }    return res;}`

Explanation:

Hi I am Samuel