Interview questions 57 -. II and the number of consecutive positive sequence s

topic:

 

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

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

 

answer:

method 1:

Violence to get away wailing

class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
        vector<vector<int>> res;
        vector<int> cur;
        for(int i=target/2+1;long(i)*(i+1)>=2*target;--i){
            int p=target,j=i;
            while(p>0 and p>=j){
                p - = j;
                - j;
            }
            if(p==0){
                for(int k=j+1;k<=i;++k){
                    cur.emplace_back(k);
                }
                res.emplace_back(move(cur));
            }
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

Method 2:

Sliding window, because it is the consecutive numbers and, quite obviously use a sliding window. . A message can notice this point should be done when the question. o ()︿)) o Oh

class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
        vector<vector<int>> res;
        int le=1,ri=1,cur_sum=0;
        while(ri<target/2+3){
            while(cur_sum<target){
                cur_sum + = ++ with ;
            }
            if(cur_sum==target){
                res.push_back({});
                for(int i=le;i<ri;++i){
                    res.back().emplace_back(i);
                }
                cur_sum + = ++ with ;
            }
            else{//>
                while(cur_sum>target){
                    cur_sum - = le ++ ;
                }
            }
        }
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/FdWzy/p/12430350.html