Yingying

你必须非常努力,才能看起来毫不费力

167. Two Sum II - Input array is sorted**

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


My code:

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        n = len(numbers)
        low = 0
        high = n-1
        sums=numbers[low]+numbers[high]
        while sums!=target:
            if sums >target:
                high -=1
            else:
                low +=1
            sums=numbers[low]+numbers[high]
        return low+1, high+1


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/alwaystry/article/details/52356726
个人分类: leetcode
上一篇88. Merge Sorted Array*
下一篇Active learning by querying informative and representative examples
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭