剑指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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值