167.Two Sum II - Input array is sorted
题意:
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.
给一个已经按照升序排列的整数数组,找到两个数字,他们的和与给定数字相等。
注意:返回的两个指数也要按照升序排列,并且指数从1开始。
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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
我的解法 : 二分查找法[Accepted]
我的思路:
首先看题意,有序数组,在有序数组中查找首先想到的就是二分查找方法。
* 需要考虑的特殊情况,当数组中有重复的数字时,比如输入[2,2], target = 4;的情况下,
* 二分查找永远查到的是第一个2,这样需要查找两次。
public int[] twoSum(int[] numbers, int target) {
int[] ans = new int[2];
for(int i = 0; i < numbers.length; i++){
int k = select(numbers, target - numbers[i], 0, numbers.length-1);
if(k != 0 && k != i + 1){
ans[0] = Math.min(i + 1, k);
ans[1] = Math.max(i + 1, k);
return ans;
}
}
return ans;
}
//用递归的方法写的二分查找
public int select(int[] numbers, int target, int lo, int hi) {
if(lo > hi){
return 0;
}
int mid = lo + (hi - lo) / 2;
if (numbers[mid] == target) {
return mid + 1;
}
if (numbers[mid] > target) {
return select(numbers, target, lo, mid - 1);
} else if (numbers[mid] < target) {
return select(numbers, target, mid + 1, hi);
}
return 0;
}
//不用递归,用循环的方法写的二分查找
public int select2(int[] numbers, int key){
int lo = 0;
int hi = numbers.length;
while(lo <= hi){
int mid = lo + (hi - lo)/2;
if(numbers[mid] == key){
return mid + 1;
}else if(numbers[mid] < key){
lo = mid + 1;
}else{
hi = mid - 1;
}
}
return 0;
}
方法二:简介,充分利用了有序数组
在数组首尾设置两个指针,当二者之和大于目标值时,后面的指针向前移;
当二者之和小于目标值时,前面的指针向后移。
public int[] twoSum2(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
int comp = numbers[left] + numbers[right];
if (comp == target) {
return new int[] { left + 1, right + 1 };
} else if (comp > target) {
right--;
} else {
left++;
}
}
return null;
}