关闭

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

63人阅读 评论(0) 收藏 举报
分类:

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:60340次
    • 积分:3898
    • 等级:
    • 排名:第8480名
    • 原创:332篇
    • 转载:90篇
    • 译文:0篇
    • 评论:11条
    最新评论