剑指offer-和为S的连续正数序列(python)

思路:两个动态指针,因为是正整数,所以既可以当做指针,也可以当做常数。sumres是等差数列求和公式。如果大于tsum,low+=1,少算一个数,如果小于tsum,high+=1,向右多算一个数。如果相等,就入栈。
特别注意:low+=1,避免重复,一直循环。

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        low=1
        high=2
        res=[]
        while low<high:
            sumres=(low+high)*(high-low+1)/2
            if sumres==tsum:
                outcome=[i for i in range(low,high+1)]
                res.append(outcome)
                low+=1
            if sumres>tsum:
                low+=1
            if sumres<tsum:
                high+=1
        return res

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104445633