https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
一 题目
给定一个已按照 非递减顺序排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length
你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。
示例 1: 输入:numbers = [2,7,11,15], target = 9 输出:[1,2] 解释:
2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
示例 2: 输入:numbers = [2,3,4], target = 6
输出:[1,3]
示例 3: 输入:numbers = [-1,0], target = -1
输出:[1,2]
提示:
2 <= numbers.length <= 3 * 104 -1000 <= numbers[i] <= 1000 numbers 按 非递减顺序 排列 -1000 <= target <= 1000
仅存在一个有效答案
二 题解—双指针遍历
class Solution {
public int[] twoSum(int[] numbers, int target) {
int length = numbers.length;
int start = 0;
int end = length - 1;
while(start<length){
while(start<end){
if(numbers[start]+numbers[end]<target){
start ++;
end = length - 1;
}
if((numbers[start]+numbers[end])==target){
return new int[]{start+1,end+1};
}
end --;
}
}
return null;
}
}
三 题解—双指针二分法
class Solution {
public int[] twoSum(int[] numbers, int target) {
int length = numbers.length;
int tagA = 0;
int tagB = length-1;
for(;tagA<length;tagA++){
int numA = numbers[tagA];
tagB = length -1;
int targetNum = target - numA;
tagB = binarySearch(numbers,tagA+1,tagB,targetNum);
if(tagB != -1){
break;
}
}
return new int[]{tagA+1,tagB+1};
}
private int binarySearch(int[] nums,int start,int end,int target){
if(nums[end]<target){
return -1;
}
while (start<=end){
int mid = start + (end - start)/2;
int midNum = nums[mid];
if(target == midNum){
return mid;
}else if(target > midNum){
start = mid +1;
}else {
end = mid ;
}
}
return -1;
}
}
四 同类型题目
leetcode 1 号算法题:两数之和
https://leetcode-cn.com/problems/two-sum/
leetcode 167 号算法题:两数之和Ⅱ - 输入有序数组
https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
leetcode 170 号算法题:两数之和Ⅲ - 数据结构设计(需Plus 会员)
https://leetcode-cn.com/problems/two-sum-iii-data-structure-design/
leetcode 653 号算法题:两数之和Ⅳ - 输入 BST
https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst/
leetcode 15 号算法题:三数之和
https://leetcode-cn.com/problems/3sum/
leetcode 18 号算法题:四数之和
https://leetcode-cn.com/problems/4sum/