167. (Two Sum II - Input array is sorted)两数之和 II - 输入有序数组
Posted OIqng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了167. (Two Sum II - Input array is sorted)两数之和 II - 输入有序数组相关的知识,希望对你有一定的参考价值。
题目:
Given an array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number.
Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
给定一个已按照非递减(升序)排列 的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
返回两个数字(1索引)的索引为大小为2的整数数组answer,其中1 <= answer[0] < answer[1] <= numbers.length。
生成的测试只有一个解决方案。同一个元素不能使用两次。
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
示例 1:
输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [1,3]
示例 2:
输入:numbers = [2,3,4], target = 6
输出:[1,3]
Example 3:
Input: numbers = [-1,0], target = -1
Output: [1,2]
示例 3:
输入:numbers = [-1,0], target = -1
输出:[1,2]
Constraints:
- 2 <= numbers.length <= 3 * 1 0 4 10^4 104
- -1000 <= numbers[i] <= 1000
- numbers is sorted in non-decreasing order.
- -1000 <= target <= 1000
- The tests are generated such that there is exactly one solution.
提示:
- 2 <= numbers.length <= 3 * 1 0 4 10^4 104
- -1000 <= numbers[i] <= 1000
- numbers 按 递增顺序 排列
- -1000 <= target <= 1000
- 仅存在一个有效答案
解题思路:
方法:双指针
我们使用双指针指向第一个元素和最后一个元素,并把他们的和与目标值target进行比较。
- 当他们相等时,发现唯一解
- 双指针的和小于目标值target时,左指针右移一位
- 双指针的和大于目标值target时,右指针左移一位
Python代码
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left, right = 0, len(numbers)- 1
while left < right:
if numbers[left] + numbers[right] == target:
return [left+1, right+1]
elif numbers[left] + numbers[right] < target:
left += 1
else:
right -= 1
return null
Java代码
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
if (numbers[left] + numbers[right] == target) {
return new int[]{left + 1, right + 1};
} else if (numbers[left] + numbers[right] < target) {
++left;
} else {
--right;
}
}
return null;
}
}
C++代码
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0, right = numbers.size() - 1;
while (left < right) {
if (numbers[left] + numbers[right] == target) {
return {left + 1, right + 1};
} else if (numbers[left] + numbers[right] < target) {
++left;
} else {
--right;
}
}
return {};
}
};
复杂度分析
时间复杂度:O(n),其中 n 是数组的长度。
空间复杂度:O(1)。
以上是关于167. (Two Sum II - Input array is sorted)两数之和 II - 输入有序数组的主要内容,如果未能解决你的问题,请参考以下文章
167. Two Sum II - Input array is sorted
167. Two Sum II - Input array is sortedeasy
167. Two Sum II - Input array is sorted
LeetCode167. Two Sum II - Input array is sorted