剑指offer全集详解python版——和为S的连续正数序列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41679411/article/details/86490053

题目描述:
找出所有和为S的连续正数序列。

思路:

双指针。

代码

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        if tsum < 3:
            return []
        small = 1
        big = 2
        middle = (tsum + 1)>>1
        curSum = small + big
        output = []
        while small < middle:
            if curSum == tsum:
                output.append(range(small, big+1))
                big += 1
                curSum += big
            elif curSum > tsum:
                curSum -= small
                small += 1
            else:
                big += 1
                curSum += big
        return output

猜你喜欢

转载自blog.csdn.net/weixin_41679411/article/details/86490053
今日推荐