题解 | #滑动窗口的最大值#
滑动窗口的最大值
http://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788
暴力:
vector<int> maxInWindows(const vector<int>& num, unsigned int size) { if (num.size() < size || size == 0) return { }; vector<int> ans; for (int i = 0; i <= num.size() - size; ++i) { ans.emplace_back(*max_element(num.begin() + i, num.begin() + i + size)); } return ans; }
单调队列:
class MyQueue { public: void push(int val) { while (!que_.empty() && que_.back() < val) { que_.pop_back(); } que_.emplace_back(val); } void pop(int val) { if (que_.front() == val) { que_.pop_front(); } } int max() { return que_.front(); }
private:
deque<int> que_;
};</int>
vector<int> maxInWindows(const vector<int>& num, unsigned int size) {
if (num.size() < size || size == 0) return { };
vector<int> ans;
MyQueue que;
for (int i = 0; i < num.size(); ++i) {
if (i < size - 1) {
que.push(num[i]);
} else {
que.push(num[i]);
ans.emplace_back(que.max());
que.pop(num[i - size + 1]);
}
}
return ans;
}</int></int></int>
```