当前位置:网站首页>57 - II. Continuous positive sequence with sum s

57 - II. Continuous positive sequence with sum s

2022-06-12 05:18:00 Be your goat

The finger of the sword Offer 57 - II. And for s Continuous positive sequence of

Ideas : The sliding window

  • initialization : Left boundary i=1, Boundary j=2, Elements and s=3, Result list res
  • loop : When i>=j Jump out of :
    • When s>target: Move the left border to the right i=i+1, And update elements and
    • When s<target: Moving to the right has a boundary j=j+1, And update elements and
    • When s==target: Record integer sequence , And move the left border to the right i=i+1
  • Return value :res
class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
        int i=1,j=2,sum=i+j;
        vector<vector<int>> ans;
        while(i<j){
            if(sum<target){
                j=j+1;
                sum+=j;
            }
            else if(sum>target){
                sum-=i;
                i++;
            }
            else{
                vector<int> res(j-i+1);
                for(int k=0;k<j-i+1;++k){
                    res[k]=k+i;
                }
                ans.push_back(res);
                sum-=i;
                ++i;
            }
        }
        return ans;
    }
};

Time complexity O(n) n yes target

Spatial complexity O(1)

原网站

版权声明
本文为[Be your goat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010618459304.html