美文网首页
和为s的连续整数序列

和为s的连续整数序列

作者: 九日火 | 来源:发表于2021-01-16 15:23 被阅读0次

    找出所有和为S的连续正数序列
    输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

    class Solution:
        def FindNumInSe(self, arget):
            if arget < 3:
                return []
    
            small = 1
            big = 2
            curnum = small + big
            middle = (arget + 1) // 2
            output = []
            while small < middle:
                if curnum == arget:
                    output.append(list(range(small, big)))
                while curnum > arget and small < middle:
                    curnum -= small
                    small += 1
                    if curnum == arget:
                        output.append(list(range(small, big)))
                big += 1
                curnum += big
            return output
    
        def FindNumInSe1(self, arget):
            if arget < 3:
                return []
    
            small = 1
            big = 2
            curnum = small + big
            middle = (arget + 1) // 2
            output = []
            while small < middle:
                if curnum == arget:
                    output.append(list(range(small, big)))
                elif curnum < arget:
                    big += 1
                    curnum += big
                else:
                    curnum -= small
                    small += 1
            return output
    
    package main
    
    func FindNumSe(target int) []int {
        if target < 3 {return []int{}}
        small := 1
        big := 2
        sum := 3
        for small <= target/2 + 1 {
            if sum == target {
                break
            } else if sum > target {
                sum -= small
                small++
            } else {
                big++
                sum += big          
            }
        }
        res := []int{}
        if sum == target {
            for i:=small; i<=end; i++ {
                res = append(res, i)
            }
        }
        return res
    }
    

    相关文章

      网友评论

          本文标题:和为s的连续整数序列

          本文链接:https://www.haomeiwen.com/subject/nwgkaktx.html