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.
二分搜索,O(n logn)
class Solution {
public int[] twoSum(int[] numbers, int target) {
if(numbers == null || numbers.length < 2)
return new int[0];
int[] res = new int[2];
for(int i = 0; i < numbers.length; i++) {
int index = search(numbers, target - numbers[i]);
if(index != -1 && index != i) {
res[0] = index > i ? i + 1 : index + 1;
res[1] = index > i ? index + 1 : i + 1;
return res;
}
}
return res;
}
public int search(int[] numbers, int target) {
if(target < numbers[0] || target > numbers[numbers.length - 1])
return -1;
int left = 0;
int right = numbers.length - 1;
while(left < right) {
int mid = left + (right - left) / 2;
if(numbers[mid] == target)
return mid;
if(numbers[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return numbers[left] == target ? left : -1;
}
}
Two Pointer, O(n),这种方法更合理一些
class Solution {
public int[] twoSum(int[] numbers, int target) {
if(numbers == null || numbers.length < 2)
return new int[0];
int[] res = new int[2];
int left = 0;
int right = numbers.length - 1;
while(numbers[left] + numbers[right] != target) {
if(numbers[left] + numbers[right] > target)
right--;
else
left++;
}
res[0] = left + 1;
res[1] = right + 1;
return res;
}
}