题目
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
解析
认真读题,题目中说两个数加起来等于target,并且这两个数在有序数组中是一定存在的,有唯一解。于是,这题就变的简单了。
使用两个指针,一个在左侧,一个在右侧,依次向前,如果两个数的和等于target,即为目标解;如果大于,则--right;小于,则++left。最终找到目标解。
代码(C语言)
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
if (numbers == NULL || numbersSize == 1) {
(* returnSize) = 0;
return NULL;
}
int left = 0, right = numbersSize - 1;
int* returnArr = (int*)malloc(sizeof(int) * 2);
(* returnSize) = 2;
while (left < right) {
if ((numbers[left] + numbers[right]) == target) {
returnArr[0] = left + 1;
returnArr[1] = right + 1;
return returnArr;
} else if ((numbers[left] + numbers[right]) > target) {
--right;
} else
++left;
}
return NULL;
}