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

和为S的连续正数序列

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param sum int整型 
 * @return int整型二维数组
 */
export function FindContinuousSequence(sum: number): number[][] {
    // write code here
    const result = []
    //定义两个指针,从前往后遍历,直到low == high的时候停止遍历
    let low = 1,high = 2
    while(low < high){
        const current = (high - low + 1)*(low  + high) / 2
        if(current === sum){
            //将这个范围的数加入到结果里
            const res = []
            for(let i = low;i <= high;i++){
                res.push(i)
            }
            //然后加入到数组里面
            result.push(res)
            low++
        }else if(current < sum){
            high++
        }else{
            low++
        }
    }
    return result
    
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务