头图

title: Daily practice (30): a continuous sequence of positive numbers whose sum is s

categories:[Swords offer]

tags:[Daily practice]

date: 2022/03/04


Daily practice (30): a sequence of consecutive positive numbers whose sum is s

Input a positive integer target, output all consecutive positive integer sequences (at least two numbers) whose sum is target.

The numbers in the sequence are arranged from small to large, and the different sequences are arranged from small to large according to the first number.

Example 1:

Input: target=9

Output: [[2,3,4],[4,5]]

Example 2:

Input: target=15

Output: [[1,2,3,4,5],[4,5,6],[7,8]]

limit:

1 <= target <= 10^5

Source: LeetCode

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

Method 1: Violent Summation Formula

vector<vector<int>> findContinuousSequence(int target) {
    if (target < 3) {
        return {};
    }
    int left = 1;
    double right = 2.0;
    vector<vector<int>> res;
    while (left < right) {
        right = (-1 + sqrt(1 + 4 * (2 * target + (long)left * left - left))) / 2;
        if (left < right && right == (int) right) {
            vector<int> ans;
            for (int i = left; i <= (int)right; i++) {
                ans.push_back(i);
            }
            res.push_back(ans);
        }
        left++;
    }
    return res;
}

Method 2: Sliding window

Algorithm flow:
1. Initialization: left border left = , right border right = 2 , sum of elements = 3 , result list res;

2. Loop: Jump out when left >= right;

  • When sum > targets: move the left border left = left + 1 to the right, and update the element and sum;
  • When sum < targets: move right border right = right + 1, and update element and sum;
  • When sum = targets: record a sequence of consecutive integers and move the left boundary to the right left = left + 1;

3. Return value: return the result list res;

vector<vector<int>> findContinuousSequence(int target) {
    if (target < 3) {
        return {};
    }
    int left = 1, right = 2, sum = 3;
    vector<vector<int>> res;
    while (left < right) {
        if (sum == target) {
            vector<int> vec;
            for (int i = left; i <= right; i++) {
                vec.push_back(i);
            }
            res.push_back(vec);
        }
        if (sum >= target) {
            sum -= left;
            left++;
        } else {
            right++;
            sum += right;
        }
    }
    return res;
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记