这道题自己思路也对了,就是数组使用出了点问题,然后就是看了别人的代码才改过来,用到匿名数组。
不多说,看代码,
class Solution {
public int[] twoSum(int[] numbers, int target) {
if(numbers==null || numbers.length < 1) return null;
int i=0, j=numbers.length-1;
while(i<j) {
int x = numbers[i] + numbers[j];
if(x<target) {//如果和小于目标值,这说明要往左边移,因为是升序数组,反之也一样
++i;
} else if(x>target) {
--j;
} else {
return new int[]{i+1, j+1};
}
}
return null;
}
}