Leetcode # 167. Two Sum II – Input Array Is Sorted

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

Solution

numbers is a 1-indexed array of integers that is already sorted in non-decreasing order

Time Complexity: O(n)
Space Complexity: O(1)

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

      if _sum > target:
        right -= 1
      else:
        left += 1

相關例題

Leetcode # 1. Two Sum

Last Updated on 2023/08/16 by A1go

目錄
Bitnami