给出一个按升序排列的数组,返回两个索引,这两个索引对应的数字和为一个特定的值
假定上述问题只有一个解决方案,并且只能遍历数组一次
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.
分析:该题是https://blog.csdn.net/wujingchangye/article/details/88541022的进阶,加了一个该数组为升序数组的条件。一般,给出数组为升序,一定要联想到索引法。就是在数组的头尾各放一个指针,一个向前一个向后,找到后就返回。 按照上面的思路给出代码:
public static int[] twoSum_inputIsSort(int[] numbers, int target) {
int left = 0;
int right = numbers.length - 1;
while (left + 1 < right) {
int cur = numbers[left] + numbers[right];
if(cur == target) {
return new int[]{left, right};
}
if(cur > target) {
right = right - 1;
} else {