3.6 and a continuous positive sequence s

topic

Enter a positive integer target, output of all consecutive positive integers, and the target sequence (containing at least two numbers).

The numbers in ascending sequence are arranged in ascending order of different sequences according to the first digit.

Example 1

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

Example 2

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

Thinking

  • Thinking sliding window. Two pointers starting point numbers 1, 2. Seeking interval and,
    • If the interval is greater than S, the pointer to the left by one.
    • If less than S, the right side of the pointer plus one.
    • If the interval is equal to S sequence is found, to find a sequence, plus a pointer to the left, keep looking.
  • You can use the summation formula of arithmetic progression: ( a 0 + a n ) n 2 \frac{(a_0+a_n)n}{2}

Code

class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
        vector<vector<int>> ans;
        int lo = 1, hi = 2;

        while ( lo < hi ) {
            int sum = ( hi - lo + 1 ) * ( lo + hi ) >> 1;

            if ( sum == target ) {
                addSequence( lo, hi, ans );
                ++lo;
            }
            else if ( sum > target )
                ++lo;
            else if ( sum < target ) 
                ++hi;
        }

        return ans;
    }

    void addSequence( int lo, int hi, vector<vector<int>>& ans ) {
        vector<int> temp;

        while ( lo <= hi )
            temp.push_back( lo++ );

        ans.push_back( temp );

        return;
    }
};
He published 183 original articles · won praise 43 · views 60000 +

Guess you like

Origin blog.csdn.net/m0_37822685/article/details/104689557