题解 | #和为S的连续正数序列#

和为S的连续正数序列

https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param sum int整型 
 * @return int整型二维数组
 */
export function FindContinuousSequence(sum: number): number[][] {
    // write code here
    let start = 1
    let end = 1
    const res = []
    const halfValue = Math.ceil(sum / 2)
    let total = start
    while (start <= halfValue && end < sum) {
        if (total === sum) {
            const subValue = []
            let i = start
            while (i <= end) {
                subValue.push(i)
                i++
            }
            res.push(subValue)
            start++
            end = start
            total = start
        } else if (total < sum) {
            end++
            total += end
        } else if (total > sum) {
            start++
            end = start
            total = start
        }
    }
    return res
}

全部评论

相关推荐

这算盘打的
程序员小白条:都这样的,都是潜规则,你自己说可以实习一年就行了,实习可以随便跑路的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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