My classical and easy understand implement in c++


  • 0
    J
    class Solution {
    public:
        vector<int> maxSlidingWindow(vector<int>& nums, int k) {
            deque<int> q;
            vector<int> r;
            for(int i=0; i<nums.size(); ++i) {
                if (q.empty()) q.push_back(i);
                else if (nums[q.front()] <= nums[i]) {
                    q.clear(); q.push_back(i);
                } else {
                    if (q.front() + k <= i) q.pop_front();
                    while(nums[q.back()] <= nums[i]) {
                        q.pop_back();
                    }
                    q.push_back(i);
                }
                if (i >= (k-1)) {
                    r.push_back(nums[q.front()]);
                }
            }
            return r;
        }
    };

  • 0
    W

    I found sometimes q becomes empty, so I think you need to check the emptiness.

                while(!q.empty() && nums[q.back()] <= nums[i]) {
                    q.pop_back();
                }
    

    BTW: I just curious about how do you figure out this kind of index operation? Is there any book mentioned such algorithm?


Log in to reply
 

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