Given an ordered array is sorted in ascending order according to find the two numbers such that their sum is equal to the sum of the target number. Function should return the two index values and index1 index2, which must be less than index1 index2. Description: Returns the index value (index1, index2 and) is not zero. You can assume that each input corresponding to only the only answer, but you can not reuse the same elements. Example: Input: Numbers = [ 2 , 7 , . 11 , 15 ], target = 9 Output: [ 1 , 2 ] Explanation: 2 and 7 is equal target number 9 . Accordingly = index1, . 1 , index2 = 2 .
1 int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){ 2 int i=0 , j=numbersSize-1 ,k; 3 int *res = malloc(sizeof(int)*2); 4 *returnSize = 2; 5 while (i <= j) 6 { 7 k = numbers[i]+numbers[j]; 8 if (k == target) 9 { 10 res[0] = i+1; 11 res[1] = j+1; 12 break; 13 } 14 else if (k > target) 15 j --; 16 else 17 i ++; 18 } 19 20 return res; 21 }
Problem-solving ideas:
Double pointer disposed on both ends of the boundary of the array,
And two target values obtained by approximating the intermediate numbers.