题解 | #滑动窗口的最大值# #单调队列
滑动窗口的最大值
https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788
class Solution { public: deque<int> que; queue<int> data; unsigned int size; int MaxVal() { if (que.empty()) return 0; return que.front(); } void PushData(const int &val) { data.push(val); while (!que.empty() && que.back() < val) { que.pop_back(); } que.push_back(val); } void PopData() { if (data.empty()) { return ; } if (data.size() != size + 1) { return ; } int front = data.front(); data.pop(); if (!que.empty() && que.front() == front) { que.pop_front(); } } vector<int> maxInWindows(const vector<int>& num, unsigned int size) { this->size = size; vector<int> ret; for (size_t i = 0; i < num.size(); ++i) { PushData(num[i]); PopData(); if (i >= size - 1) ret.push_back(MaxVal()); } return ret; } };