【leetcode】167.Two Sum II

题目描述
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.
给定一个升序排列的序列,找到相加等于一个确定目标值的两个数字,并返回它们在序列中的位置。

思路
这道题我们可以采用二分查找法。

代码

class Solution:
    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:
                return [l+1,r+1]
            if numbers[l] + numbers[r] < target:
                l += 1
            if numbers[l] + numbers[r] > target:
                r -= 1

猜你喜欢

转载自blog.csdn.net/qq_42011358/article/details/83478364