# 题目167:两数之和 II – 输入有序数组

## 解法1 暴力法

``````//解法1 暴力求解
public int[] twoSum(int[] numbers, int target) {

int[] indexes = new int[2];
for (int i = 0; i < numbers.length-1; i++) {
for (int j = i+1; j<numbers.length;j++){
if (numbers[i]+numbers[j]==target){
indexes[0] = i+1;
indexes[1] = j+1;
return indexes;
}
}
}
return indexes;
}
``````

## 解法2 二分搜索

``````//解法2 二分搜索法
public int[] twoSum2(int[] numbers, int target) {
int[] indexes = new int[2];
for (int i = 0; i < numbers.length-1; i++) {
int index2 = binarySearch(numbers,i+1,numbers.length-1,target-numbers[i]);
if (index2>-1){
indexes[0] = i+1;
indexes[1] = index2+1;
return indexes;
}
}
return indexes;

}
private int binarySearch(int[] nums , int l , int r , int target){
if (l>=r){
if (nums[l]==target){
return l;
}else {
return -1;
}
}else {
int mid = l+(r-l)/2;
if (nums[mid]==target){
return mid;
}else if (nums[mid]>target){
return binarySearch(nums,l,mid-1,target);
}else {
return binarySearch(nums,mid+1,r,target);
}
}
}
``````

## 解法3 对撞指针

``````//解法3 对撞指针
public int[] twoSum3(int[] numbers, int target){
int[] indexes = new int[2];
int l = 0;
int r = numbers.length-1;
while (l<=r){
if (numbers[l]+numbers[r]==target){
indexes[0] = l+1;
indexes[1] = r+1;
return indexes;
}else if (numbers[l]+numbers[r]>target){
r--;
}else {
l++;
}
}
return indexes;
}
``````