面试题57 - II. 和为s的连续正数序列

2020-03-06  本文已影响0人  最尾一名

原题

https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/

解题思路

滑动窗口,left、right 分别表示当前窗口的左右边界(左闭右开)

代码

/**
 * @param {number} target
 * @return {number[][]}
 */
var findContinuousSequence = function(target) {
    const result = [];
    let left = 1, right = 1, currentSum = 0;
    while (left < target / 2) {
        if (currentSum < target) {
            currentSum += right;
            ++right;
        } else if (currentSum > target) {
            currentSum -= left;
            ++left;
        } else {
            const temp = [];
            for (let i = left; i < right; ++i) {
                temp.push(i);
            }
            result.push(temp);
            currentSum -= left;
            ++left;
        }
    }
    return result;
};

复杂度

上一篇 下一篇

猜你喜欢

热点阅读