Sharing my code without using deque


  • 0
    S
    class Solution {
    public:
        vector<int> maxSlidingWindow(vector<int>& n, int k) {
            vector<int> res;
            if(k>n.size()||k==0) return res;
            if(k==1) return n;
            int start=0, stop=0, curMax=n[0], curMaxIndex=0;
            
            for(int i=0; i<k; ++i){
                curMax=max(curMax, n[i]);
                if(n[i]==curMax) curMaxIndex=i;
                ++stop;
            }
            
            for(start=0, stop=k;stop<=n.size();++stop, ++start){
                if(curMaxIndex<start){
                    curMax=n[start];
                    for(int i=0; i<k; ++i){
                        curMax=max(curMax, n[i+start]);
                        if(n[i+start]==curMax) curMaxIndex=i+start;
                    }
                }
                if(n[stop-1]>=curMax){
                    curMax=n[stop-1];
                    curMaxIndex=stop-1;
                }
                res.push_back(curMax);
            }
            
            return res;
        }
        
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.