输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例:
1 2 3 4 5
| 输入:nums = [2,7,11,15], target = 9 输出:[2,7] 或者 [7,2]
输入:nums = [10,26,30,31,47,60], target = 40 输出:[10,30] 或者 [30,10]
|
解法
方法一:二分查找
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-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: left,right = 0, len(nums) -1 while left < right: sum = nums[left] + nums[right] if target == sum: return [nums[left],nums[right]] elif sum > target: right -= 1 else: left += 1 return []
|