Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

剑指 Offer 57 - II. 和为s的连续正数序列 #85

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

剑指 Offer 57 - II. 和为s的连续正数序列

输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。

序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。

Example 1

输入:target = 9
输出:[[2,3,4],[4,5]]

Example 2

输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]

Note

Tcdian commented 4 years ago

Solution

/**
 * @param {number} target
 * @return {number[][]}
 */
var findContinuousSequence = function(target) {
    const n = Math.ceil(target / 2);
    let i = 1;
    let j = 2;
    let sum = 3;
    const result = [];

    while (j <= n) {
        if (sum < target) {
            j++;
            sum += j;
        } else if (sum > target) {
            sum -= i;
            i++;
        } else {
            result.push(Array.from(new Array(j - i + 1), (v, index) => i + index));
            sum -= i;
            i++;
            j++;
            sum += j;
        }
    }

    return result;
};