question describe:
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
1、先二叉查找找到小于target-number[0]的临界点k(注意,不是target的临界点)
2、使用 2个point,指向第一个和k,遍历
public class Solution {
public int[] twoSum(int[] numbers, int target) {
if(numbers[0]>target) return null;
int id = 0;
if(numbers[numbers.length-1]<=target)
{
id = numbers.length-1;
}else
id = binarySearch(numbers, target-numbers[0], 0, numbers.length-1);
int i = 0, j = id;
while(i<j)
if(numbers[i] + numbers[j] == target)
{
// System.out.println(i+","+j);
return new int[]{i+1,j+1};
}else
{
if(numbers[i] + numbers[j] > target)
{
j -- ;
}else
{
i ++;
}
}
return null;
}
private int binarySearch(int[] numbers, int target,int i, int j)
{
if(i == j || i>j)
{
return i;
}
int mid = (i+j)>>1;
if(numbers[mid] > target)
{
return binarySearch(numbers, target, i, mid-1);
}else
if(numbers[mid] < target)
{
return binarySearch(numbers, target, mid+1, j);
}else
return mid;
}
}
167. Two Sum II
最新推荐文章于 2019-11-14 13:05:20 发布