-
Notifications
You must be signed in to change notification settings - Fork 0
167. Two Sum II Input array is sorted
Jacky Zhang edited this page Oct 27, 2016
·
2 revisions
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
Array类题目。
解题思路为two pointers。采用binary search应该可以进一步提高性能。
##Approach 1: two pointers
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
int i1 = 0;
int i2 = numbers.length - 1;
while(i1 < i2) {
int sum = numbers[i1] + numbers[i2];
if(sum == target) {
res[0] = i1 + 1;
res[1] = i2 + 1;
break;
} else if(sum > target) {
i2--;
} else {
i1++;
}
}
return res;
}
}##Approach 2: binary search
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
int l = 0;
int r = numbers.length-1;
while(l < r) {
int sum = numbers[l] + numbers[r];
if(sum == target) {
res[0] = l + 1;
res[1] = r + 1;
break;
} else if(sum > target) {
r = binarySearch(numbers, target-numbers[l], l, r-1, true);
} else {
l = binarySearch(numbers, target-numbers[r], l+1, r, false);
}
}
return res;
}
private int binarySearch(int[] numbers, int target, int l, int r, boolean smaller) {
while(l <= r) {
int m = l + (r - l) / 2;
if(numbers[m] == target) {
return m;
} else if(numbers[m] > target) {
r = m - 1;
} else {
l = m + 1;
}
}
if(smaller) {
return r;
}
return l;
}
}