Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Tcdian opened this issue Mar 25, 2020 · 1 comment
Open

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

Tcdian opened this issue Mar 25, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Mar 25, 2020

剑指 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

  • 1 <= target <= 10^5
@Tcdian
Copy link
Owner Author

Tcdian commented Mar 25, 2020

Solution

  • JavaScript 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;
};

@Tcdian Tcdian changed the title 《剑指 Offer(第 2 版)》57 - II. 和为s的连续正数序列 剑指 Offer 57 - II. 和为s的连续正数序列 Jun 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant