这道题要是用哈希的话,时间复杂度也是 O(n),但是也可以不适用额外空间达到O(n),也是我们经常适用的方法,双指针法
// 这个是金典的 两数和 的问题,如何在o(n)的时间复杂度内完成呢?
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] an = new int[2];
int size = numbers.length;
int index1 = 0;
int index2 = size-1;
int sum;
while(index1 < index2){
sum = numbers[index1]+numbers[index2];
if(sum > target){
index2--;
} else if(sum < target){
index1++;
} else {
break;
}
}
an[0] = index1+1;
an[1] = index2+1;
return an;
}
}