Question Link:

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


I have talked about different versions of the “Two Sum” problem in my university web page

[LeetCode 1] Two Sum with unsorted array

Solution

The solution is just the simpler version of the $O(n)$ method with sorted array in my post above, where we scan the array from the both ends.

Implementation

[-] Python code accepted by LeetCode OJ
class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        low = 0
        high = len(numbers) - 1
        
        while low < high:
            s = numbers[low] + numbers[high]
            if s == target:
                return [low + 1, high + 1]
            elif s < target:
                # Need to increase low
                tmp = numbers[low]
                low += 1
                while numbers[low] == tmp and low < high:
                    low += 1
            elif s > target:
                # Need to decrease high
                tmp = numbers[high]
                high -= 1
                while numbers[high] == tmp and low < high:
                    high -= 1
        # Not found
        return None