剑指 Offer 57. 和为s的两个数字

52 阅读1分钟

图片.png

思路

双指针:

  • 如果指针大于s则右指针左移
  • 反之则左指针右移

参考: leetcode.cn/problems/he…

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        left = 0
        right = len(nums)-1
        while left < right:
            if nums[left] + nums[right] == target:
                return nums[left],nums[right]
            elif nums[left] + nums[right] > target:
                # 右指针左移
                right-=1
            else:
                # 左指针右移
                left +=1