给定一个已按照 升序排列 的整数数组 numbers
,请你从数组中找出两个数满足相加之和等于目标数 target
。
函数应该以长度为 2
的整数数组的形式返回这两个数的下标值。numbers
的下标 从 0 开始计数 ,所以答案数组应当满足 0 <= answer[0] < answer[1] < numbers.length
。
假设数组中存在且只存在一对符合条件的数字,同时一个数字不能使用两次。
示例 1:
输入:numbers = [1,2,4,6,10], target = 8 输出:[1,3] 解释:2 与 6 之和等于目标数 8 。因此 index1 = 1, index2 = 3 。
示例 2:
输入:numbers = [2,3,4], target = 6 输出:[0,2]
示例 3:
输入:numbers = [-1,0], target = -1 输出:[0,1]
提示:
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers
按 递增顺序 排列-1000 <= target <= 1000
- 仅存在一个有效答案
注意:本题与主站 167 题相似(下标起点不同):https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/
双指针
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
i, j = 0, len(numbers) - 1
while True:
if numbers[i] + numbers[j] < target:
i += 1
elif numbers[i] + numbers[j] > target:
j -= 1
else:
return [i, j]
class Solution {
public int[] twoSum(int[] numbers, int target) {
int i = 0, j = numbers.length - 1;
for (;;) {
if (numbers[i] + numbers[j] < target) {
i++;
} else if (numbers[i] + numbers[j] > target) {
j--;
} else {
return new int[] {i, j};
}
}
}
}
func twoSum(numbers []int, target int) []int {
for i, j := 0, len(numbers)-1; ; {
if numbers[i]+numbers[j] < target {
i++
} else if numbers[i]+numbers[j] > target {
j--
} else {
return []int{i, j}
}
}
}
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i = 0;
int j = numbers.size() - 1;
vector<int> res;
while (i < j) {
int sum = numbers[i] + numbers[j];
if (sum < target) {
i++;
} else if (sum > target) {
j--;
} else {
res.push_back(i);
res.push_back(j);
break;
}
}
return res;
}
};
use std::cmp::Ordering;
impl Solution {
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
let n = numbers.len();
let mut l = 0;
let mut r = n - 1;
loop {
match target.cmp(&(numbers[l] + numbers[r])) {
Ordering::Less => r -= 1,
Ordering::Greater => l += 1,
Ordering::Equal => break,
}
}
vec![l as i32, r as i32]
}
}
use std::cmp::Ordering;
impl Solution {
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
let n = numbers.len();
for i in 0..n - 1 {
let num = target - numbers[i];
let mut l = i + 1;
let mut r = n - 1;
while l <= r {
let mid = l + (r - l) / 2;
match num.cmp(&numbers[mid]) {
Ordering::Less => r = mid - 1,
Ordering::Greater => l = mid + 1,
Ordering::Equal => return vec![i as i32, mid as i32],
}
}
}
vec![-1, -1]
}
}