Two Sum II – Input array is sorted – Python 3 (Week 18 – 08)

class Solution:
    """
    @param nums: an array of Integer
    @param target: target = nums[index1] + nums[index2]
    @return: [index1 + 1, index2 + 1] (index1 < index2)
    """
    def twoSum(self, nums, target):
        # write your code here
        
        if not nums or target is None:
            return None
            
        l, r = 0, len(nums) - 1
        
        while l < r:
            value = nums[l] + nums[r]
            if value == target:
                return [l + 1, r + 1]
            if value < target:
                l += 1
            else:
                r -= 1
            
        return None

Leave a comment

Design a site like this with WordPress.com
Get started