Two Sum II - Input array is sorted

Problem: Two Sum II - Input array is sorted

The difference between this question and the simple one is that the input array is sorted, which means the smallest number is at first and largest number is at last. We can use two pointers, left one points to the first number and right one points to the right number. If the sum of these two numbers are smaller than target, which means our left-hand number is too small (our right-hand number cannot be bigger), we just move our left pointer right 1 space. Similarly, if the sum is too big, we can move our right pointer left. By repeating doing this, we can achieve our answer.

Code in Python:

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        l, r = 0, len(numbers)-1
        while l < r:
            if numbers[l] + numbers[r] > target: r -= 1
            elif numbers[l] + numbers[r] < target: l += 1
            else: return [l+1, r+1]

results matching ""

    No results matching ""