优解
class Solution {
public int[] twoSum(int[] numbers, int target) {
int res[]={-1,-1};
int low=0,high=numbers.length-1;
while(low<high){
if((numbers[low]+numbers[high])>target){
high--;
}
else if((numbers[low]+numbers[high])<target){
low++;
}
else{
res[0]=++low;
res[1]=++high;
return res;
}
}
return res;
}
}
暴力解:
class Solution {
public int[] twoSum(int[] numbers, int target) {
int res[]={-1,-1};
for(int index1=0;index1<numbers.length-1;index1++){
for(int index2=index1+1;index2<numbers.length;index2++){
if((numbers[index1]+numbers[index2])==target){
res[0]=index1+1;
res[1]=index2+1;
System.out.println(res);
return res;
}
}
}
return res;
}
}
总结:当需要用到二重循环时,考虑是否可以用2个指针代替,降低时间复杂度。