2021-04-13

剑指 Offer 57 - II. 和为s的连续正数序列

1.这是自己写的垃圾

class Solution(object):
    def findContinuousSequence(self, target):
        """
        :type target: int
        :rtype: List[List[int]]
        """
        res=[]
        a=[]
        #i=1
        #j=2
        for tmp in range(1,target):
            i=tmp
            j=tmp+1
            total=0
            while total <target:
                total=(i+j)*(j-i+1)/2
                j=j+1
            if total == target:
                #a.append(range(i,j))
                res.append(range(i,j))
                #a=[]
            else:
                total=0
                while total > target:
                    i+=1
                    total=(i+j)*(j-i+1)/2
                if total ==target:
                    #a.append(range(i,j))
                    res.append(range(i,j))
                    #a=[]
        return res

2.大佬写的

def findContinuousSequence(self, target: int) -> List[List[int]]:
    i = 1 # 滑动窗口的左边界
    j = 1 # 滑动窗口的右边界
    sum = 0 # 滑动窗口中数字的和
    res = []

    while i <= target // 2:
        if sum < target:
            # 右边界向右移动
            sum += j
            j += 1
        elif sum > target:
            # 左边界向右移动
            sum -= i
            i += 1
        else:
            # 记录结果
            arr = list(range(i, j))
            res.append(arr)
            # 左边界向右移动
            sum -= i
            i += 1

    return res

作者:nettee
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/shi-yao-shi-hua-dong-chuang-kou-yi-ji-ru-he-yong-h/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

3.总结

自己写的其实是已经看了大概的思路,但是没有了解其深一点的特点,以及在写的时候没想到可以直接while+三重if写下午搞循环,多写多练加油嘿嘿

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值