其他分享
首页 > 其他分享> > 239.sliding-window-maxium 滑动窗口最大值

239.sliding-window-maxium 滑动窗口最大值

作者:互联网

采用双端队列deque,并且保证deque从前往后依次递减,并且出现在deque里面的相邻两数,其在原滑动窗口中,两数中间的数一定比这两个数小。为了保证这一点,在push_back()时,如果deque.back()小于要push_back()的数,则执行pop_back(),直到deque为空或者不小于为止。

#include <deque>
#include <vector>
using std::deque;
using std::vector;
class Solution {
  public:
    vector<int> maxSlidingWindow(vector<int> &nums, int k) {
        deque<int> dq;
        vector<int> res;
        for (int i = 0; i < k; i++) {
            while (!dq.empty() && nums[i] > dq.back())
                dq.pop_back();
            dq.push_back(nums[i]);
        }
        res.push_back(dq.front());
        for (int i = 1; i < nums.size() - k + 1; i++) {
            if (!dq.empty() && nums[i - 1] == dq.front()) {
                dq.pop_front();
                while (!dq.empty() && nums[i + k - 1] > dq.back())
                    dq.pop_back();
                dq.push_back(nums[i + k - 1]);
                res.push_back(dq.front());
            } else {
                while (!dq.empty() && nums[i + k - 1] > dq.back())
                    dq.pop_back();
                dq.push_back(nums[i + k - 1]);
                res.push_back(dq.front());
            }
        }
        return res;
    }
};

标签:deque,nums,back,pop,window,239,push,maxium,dq
来源: https://www.cnblogs.com/zwyyy456/p/16593125.html