跳过正文
  1. leetcode 题解/

167_两数之和_II_-_输入有序数组

·66 字·1 分钟

类型:数组

    1. 两数之和 II - 输入有序数组 💚

    https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/

    ❓ 从升序排列的数组 nums 中找出两个数相加等于 target。

    💡 双指针

    class Solution:
        def twoSum(self, numbers: List[int], target: int) -> List[int]:
            low, high = 0, len(numbers) - 1
            while low < high:
                total = numbers[low] + numbers[high]
                if total == target:
                    return [low + 1, high + 1]
                elif total < target:
                    low += 1
                else:
                    high -= 1
    
            return [-1, -1]

    时间复杂度:O(n),空间复杂度:O(1)