Leetcode

Two Sum II - Input Array Is Sorted

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

C++

class Solution {
 public:
  vector<int> twoSum(vector<int>& numbers, int target) {
    int l = 0;
    int r = numbers.size() - 1;

    while (numbers[l] + numbers[r] != target)
      if (numbers[l] + numbers[r] < target)
        ++l;
      else
        --r;

    return {l + 1, r + 1};
  }
};

JAVA

class Solution {
  public int[] twoSum(int[] numbers, int target) {
    int l = 0;
    int r = numbers.length - 1;

    while (numbers[l] + numbers[r] != target)
      if (numbers[l] + numbers[r] < target)
        ++l;
      else
        --r;

    return new int[] {l + 1, r + 1};
  }
}

Python

class Solution:
  def twoSum(self, numbers: List[int], target: int) -> List[int]:
    l = 0
    r = len(numbers) - 1

    while l < r:
      sum = numbers[l] + numbers[r]
      if sum == target:
        return [l + 1, r + 1]
      if sum < target:
        l += 1
      else:
        r -= 1