And S is a continuous sequence of positive integers (double pointer Method)

Title Description

Xiao Ming is very fond of mathematics, one day when he was doing math homework, required to calculate and 9 to 16, he immediately wrote the correct answer is 100. But he was not satisfied with this, he wondered how many kinds of continuous positive number sequence is 100 (including at least two numbers). Before long, he got another set of consecutive positive number and a sequence of 100: 18,19,20,21,22. Now the question to you, you can also quickly identify all positive and continuous sequence S? Good Luck!

Output Description:

All positive output and a continuous number sequence S. The ascending order in the ascending sequence between the sequence numbers in accordance with the start ascending order

Solving: double pointer method, (sliding window technique)

class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {
        vector<vector<int> > allRes;
        int phigh = 2,plow = 1;
         
        while(phigh > plow){
            int cur = (phigh + plow) * (phigh - plow + 1) / 2;
            if( cur < sum)
                phigh++;
             
            if( cur == sum){
                vector<int> res;
                for(int i = plow; i<=phigh; i++)
                    res.push_back(i);
                allRes.push_back(res);
                plow++;
            }
             
            if(cur > sum)
                plow++;
        }
         
        return allRes;
    }
};

 

Guess you like

Origin www.cnblogs.com/cstdio1/p/11242623.html