A clear solution using deque (C++)


  • 17
    F

    class Solution {
    public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {

        deque<int> q;
        vector<int> maxs;
        if(nums.empty()||k<=0) return maxs;
    
        for(int i=0;i<nums.size();i++){
            while(!q.empty()&&nums[q.back()]<=nums[i]) 
                q.pop_back();
            q.push_back(i);
            if(q.front()<=i-k) q.pop_front();
            
            if(i>=k-1) maxs.push_back(nums[q.front()]);
        }
        return maxs;
    }
    

    };


Log in to reply
 

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