剑指Offer42:和为S的两个数字

思路:

数列满足递增,设两个头尾两个指针low和high,

若array[low]+array[high]==tsum,就是答案(low和high相差越远乘积越小)

若array[low]+array[high]>tsum,high-=1

若array[low]+array[high]>tsum,low+= 1

# -*- coding:utf-8 -*-
class Solution:
    def FindNumbersWithSum(self, array, tsum):
        # write code here
        low=0
        high=len(array)-1
        res=[]
        while low<high:
            if array[low]+array[high]==tsum:
                res.append(array[low])
                res.append(array[high])
                low+=1
                high-=1
            elif array[low]+array[high]>tsum:
                high-=1
            else:
                low+=1
        return res[:2]

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/85334860