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

Input: numbers={2, 7, 11, 15}, target=9
Output:


思路:设置两个变量,i,j。i 从0开始向后自增,j从数组最后一位向前自减。如果当前和大于target,说明j太大了,j应该减1。如果当前和小于target,说明i太小了,i应该加1。O(n)

public int[] twoSum(int[] numbers, int target) {
int l = 0, r = numbers.length - 1;
int t = numbers[l] + numbers[r];
while(l < r && t != target) {
if(t < target) {
l++;
}else {
r--;
}
t = numbers[l] + numbers[r];
}
return new int[] {l + 1, r + 1};
}
}