1 题目描述
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]
示例 2:
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]
限制:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 解题思路
-
方法:双指针
利用 HashMap 可以通过遍历数组找到数字组合,时间和空间复杂度均为 O(N) ;
注意本题的 nums 是 排序数组 ,因此可使用 双指针法 将空间复杂度降低至 O(1) 。
-
复杂度分析:
时间复杂度 O(N) : N 为数组 nums 的长度;双指针共同线性遍历整个数组。
空间复杂度 O(1) : 变量 i, j 使用常数大小的额外空间。
作者:jyd
链接:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/solution/mian-shi-ti-57-he-wei-s-de-liang-ge-shu-zi-shuang-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3 解决代码
- 方法:双指针《Java代码》
class Solution {
public int[] twoSum(int[] nums, int target) {
int left = 0;
int right = nums.length -1;
while(left < right){
int res = nums[left] + nums[right];
//如果相等的话,创建一个新的数组直接返回
if(res == target){
return new int[]{nums[left],nums[right]};
}
//如果结果大于目标值,右边的指针往前走
else if(res > target){
right--;
}
else{
left++;
}
}
return new int[]{};
}
}
- 方法:双指针《python3 代码》
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
left = 0
right = len(nums) -1
while left < right:
res = nums[left] + nums[right]
if res == target:
return nums[left], nums[right]
elif res > target:
right -= 1
else:
left += 1
return []