LCOF劍指offer--面試題57 - II. 和爲s的連續正數序列

輸入一個正整數 target ,輸出所有和爲 target 的連續正整數序列(至少含有兩個數)。

序列內的數字由小到大排列,不同序列按照首個數字從小到大排列。

示例 1:

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

示例 2:

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

限制:

1 <= target <= 10^5

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析:
滑動窗口
解答:

class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
        vector<vector<int>> res;
        int i=1;
        int j=1;
        int sum = 0;

        while(i<target){
            if(sum<target){
                //右邊界右移
                sum+=j;
                j++;
            }
            else if(sum>target){
                //左邊界右移
                sum-=i;
                i++;
            }
            else{
                //正好
                vector<int> subres;
                for(int k=i;k<j;k++){
                    subres.push_back(k);
                }
                //左邊界右移
                res.push_back(subres);
                sum-=i;
                i++;
            }
        }

        return res;

    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章