方法1:首先遍历整个数组,每次取值相等于确定一个数,然后用target减去他,就是另一个数,然后再遍历数组看是否有这个数,有就是break
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] res=new int[2];
for(int i=0;i<numbers.length-1;i++){
int temp=numbers[i];
int next=target-temp;
for(int j=i+1;j<numbers.length;j++){
if(numbers[j]==next){
res[0]=i+1;
res[1]=j+1;
break;
}
}
}
return res;
}
}
方法2:从最小和最大的开始加,如果和大于target,则high–,小于就low++,否则就输出坐标
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] res=new int[2];
int i=0;
int j=numbers.length-1;
while(true){
if(numbers[i]+numbers[j]>target){
j--;
}
if(numbers[i]+numbers[j]<target){
i++;
}
if(numbers[i]+numbers[j]==target){
res[0]=i+1;
res[1]=j+1;
break;
}
}
return res;
}
}