連續數組和為S

和为S的连续正数序列_牛客网

https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tqId=11194&tPage=3&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        res = []
        low,high = 1,2
        while low<high:
            cursum = (low+high)*(high-low+1)/2
            if cursum == tsum:
                tmp =[]
                for i in range(low,high+1):
                    tmp.append(i)
                res.append(tmp)
                low += 1 #在當前連續數組計算完以後,連續數組的low,最小值要繼續+1,以便尋找下一個和為s的連續數組
            elif cursum<tsum:
                high+= 1
            else:
                low += 1
        return res


窮舉法:運用等差數列求和公式,左右指針,如果當前數列的和正好等於所給的數字,那麼append,加入進去以後,low指針要加1 ,以便尋找下一組和為S的連續數組,如果當前和小於所給數字,high+1,若大於,low+1。
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
05-22 09:23
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务