原题链接: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
1. 题目描述
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.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
和2Sum类似,但是给的数组已经排好序了。
2. 解题思路
采用二分,两个下标,一个从头移动,一个从尾部移动,直到发现和为target。
我的代码:用时1ms。
实现代码
class Solution {
int[] res = new int[2];
public int[] twoSum(int[] numbers,int target) {
int l = 0;
int r = numbers.length-1;
while(l<r) {
int sum = numbers[l] + numbers[r];
if(sum > target) {
r--;
}
else if (sum <target ) {
l++;
}
else {
res[0] = l+1;
res[1] = r+1;
break;
}
}
return res;
}
}
在Discuss里面看到两个0ms,Beats100%的答案,也放在这里吧。
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int i = 0, j = numbers.length-1;
int sum;
while (i < j) {
sum = numbers[i] + numbers[j];
if (sum == target)
return new int[]{i+1, j+1};//直接返回数组,这是比我快的主要原因
else if (sum < target)
i++;
else
j--;
}
return null;
}
}
第二个:不再采用简单的l++和r–,而是用二分的方法调整l、r
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/51349/0-ms-Binary-Search-Solution
public class Solution {
//high:寻找比target小,但是其右边比target大的坐标
//low:寻找比target大,但是左边比target小的坐标
public int[] twoSum(int[] numbers, int target) {
int low = 0;
int high = numbers.length-1;
while(low < high) {
if((numbers[low] + numbers[high]) > target) {
int start = low+1;
int end = high;
while(start < end) {
int mid = (start+end)/2;
if((numbers[low] + numbers[mid]) > target) {
end = mid-1;
}else if((numbers[low] + numbers[mid]) < target) {
start = mid+1;
}else{
end = mid;
break;
}
}
if((numbers[low] + numbers[end]) > target) end--;
high = end;
}else if((numbers[low] + numbers[high]) < target) {
int start = low;
int end = high-1;
while(start < end) {
int mid = (start+end)/2;
if((numbers[high] + numbers[mid]) > target) {
end = mid-1;
}else if((numbers[high] + numbers[mid]) < target) {
start = mid+1;
}else{
end = mid;
break;
}
}
if((numbers[end] + numbers[high]) < target) end++;
low = end;
}else{
break;
}
}
return new int[]{low+1, high+1};
}
}
3. n-Sum专题相关题目
1. Two Sum
15. 3Sum
16. 3Sum Closest
18. 4Sum
167. Two Sum II - Input array is sorted
560. Subarray Sum Equals K
653. Two Sum IV - Input is a BST