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

找规律版

# -*- coding:utf-8 -*-
from math import sqrt, ceil
class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        if tsum<=2:
            return []
        maxn = int(sqrt(2*tsum+1))
        res = []
        for n in range(maxn, 1, -1):
            # n为奇数
            if (n&1)==1 and tsum%n==0:
                center = tsum//n
                low = center - (n//2)
                high = center +(n//2)
                if low == 0:
                    continue
                res.append(list(range(low, high+1)))
            # n为偶数
            elif (n&1==0) and (tsum%n)*2==n:
                center = tsum//n
                low = center -(n//2)+1
                high = center +(n//2)
                if low == 0:
                    continue
                res.append(list(range(low, high+1)))
        return res


双指针+滑动窗口版

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        res = []
        plow = 1
        phigh = 2
        while plow<phigh:
            total = (plow+phigh)*(phigh-plow+1)/2
            if total == tsum:
                res.append(list(range(plow, phigh+1)))
                plow+=1
            elif total<tsum:
                phigh+=1
            elif total > tsum:
                plow+=1
        return res

猜你喜欢

转载自blog.csdn.net/weixin_42766102/article/details/89679843