题目
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. Please note that 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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解法(看答案后才知道的)
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
int s = 0;
int e = numbers.length - 1;
// 从左右两头分别查找,根据结果来移动两端指针。
// n[s] + n[e] <= target or target <= n[s] + n[e]
while(s <= e){
int sum = numbers[s] + numbers[e];
if(sum > target)
e = e - 1;
else if(sum < target)
s = s + 1;
else{
res[0] = s + 1;
res[1] = e + 1;
break;
}
}
return res;
}
}