Python concise two pointers solution


  • -1
    C

    Since each input would have exactly one solution, we write the loop invariant as the following.

    class Solution(object):
        def twoSum(self, numbers, target):
            head = 0
            tail = len(numbers) - 1
            while numbers[head] + numbers[tail] != target:
                if numbers[head] + numbers[tail] > target:
                    tail -= 1
                else:
                    head += 1
            return [head + 1, tail + 1]
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.