167. Two Sum II - Input array is sorted (在有序数组中确定和为给定值的两个元素的下标)

时间:2022-04-02 22:07:33

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

题目大意:确定两个数a,b,在升序数组中numbers[]中,numbers[a-1] + numbers[b-1] = target(因为a,b从1开始),以数组形式返回a,b。

题目思路:

解法一:双指针,一个从左边开始,一个从右边开始,如果和比target小,则左边指针右移,如果和比target大,则右边指针左移,直到和等于target为止。代码如下:(1ms,beats 40.41%)

public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
int[] res = new int[2];
while (left != right) {
while (target > numbers[left] + numbers[right])
left++;
while (target < numbers[left] + numbers[right])
right--;
if (target == numbers[left] + numbers[right]) {
res[0] = left + 1;
res[1] = right + 1;
return res;
}
;
}
return res;
}


解法二:使用双指针+二分查找。首先令start = 0,end = numbers.length-1。比较:

若numbers[start] + numbers[end] < target , 则 start 不动,使用二分查找法在 [start+1,end-1]中确定新的end值,比较对象为target - numbers[start] ;

若numbers[start] + numbers[end] > arget , 则 end 不动,使用二分查找法在 [start+1,end-1]中确定新的start值,比较对象为target - numbers[end] ;

否则找到正确结果,返回结果数组。

代码如下:(0ms,beats 98.04%)

注意该二分查找中的循环判断条件,是 while (start<end) ,而非一般二分查找的 while (start<=end),这是因为我们在这里确定end值(或start值)时,不保证一定找到end使numbers[end] = 比较对象,只是确定一个位置,以便进行下一次比较。 使用 while (start<=end) 可能导致无限循环,例如当numbers[] ={3,24,50,79,88,150,345},target=200。


public int[] twoSum(int[] numbers, int target) {
int start = 0,end = numbers.length - 1;
int[] res = new int[2];
while (start < end) {
int value = numbers[start] + numbers[end];
if (value == target) {
res[0] = start+1;
res[1] = end+1;
return res;
} else if (value < target) {
start = binarySearch(numbers, start + 1, end - 1, target - numbers[end]);
} else {
end = binarySearch(numbers, start + 1, end - 1, target - numbers[start]);
}
}
return res;
}

private int binarySearch(int[] nums, int start, int end, int target) {
while (start < end) { //注意是<,而非一般二分查找的 <=
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return start;
}