gary@interview:~/interview/coding/167-two-sum-ii-i….md$
$ cat ./coding/167-two-sum-ii-input-array-is-sorted.md
[Coding]

167. Two Sum II - Input array is sorted

────────────────────────────────────────────────────────────

167. Two Sum II - Input array is sorted

如果已經排序好了,可以直接用 2 Sum 雙指針的方法。

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

        return [-1, -1]

--tags#Classic
$ ls ./coding/ | grep -v 167-two-sum-ii-input-array-is-sorted
265. Paint House II256. Paint House143. Reorder List1762. Buildings With an Ocean View
← cd ../codingcd ~