找到两个值加起来和为target
使用二分查找。
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] num=new int[2];
for(int i=0;i<numbers.length;i++){
//从下一个元素之后查找target-numbers[i]
int index=BinarySerch(numbers,i+1,target-numbers[i]);
if(index!=-1){
num[0]=i+1;
num[1]=index+1;
}
}
return num;
}
public int BinarySerch(int[] arr,int startIndex,int e){
int low=startIndex;
int high=arr.length-1;
while(low<=high){
int mid=low+(high-low)/2;
if(arr[mid]==e)
return mid;
else if(arr[mid]<e)
low=mid+1;
else
high=mid-1;
}
return -1;
}
}