LeetCode刷题实战167:两数之和 II - 输入有序数组
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.
题意
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
解题
思路1:双层循环
class Solution {
public int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
int Num = target - numbers[i];
for (int j = i + 1; j < numbers.length; j++) {
if (Num == numbers[j]){
int nums[] = {i+1,j+1};
return nums;
}
}
}
return null;
}
}
思路2:双指针
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left=0;
int right=numbers.length-1;
while(leftint sum=numbers[left]+numbers[right];
if(sum==target)return new int[]{left+1,right+1};
else if(sumelse if(sum>target)right--;
}
return null;
}
}
思路3:二分查找
class Solution {
public int[] twoSum(int[] numbers, int target) {
for(int i = 0; i < numbers.length; i++) {
int index = binarySearchIndex(numbers, i + 1, target - numbers[i]);
if(index != -1) {
return new int[]{i + 1, index + 1};
}
}
return new int[]{};
}
public int binarySearchIndex(int[] numbers, int startIndex, int target) {
int low = startIndex;
int high = numbers.length - 1;
while(low <= high) {
int mid = (low + high) >>> 1;
if(target > numbers[mid]) {
low = mid + 1;
} else if(target < numbers[mid]) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}
}
