-
Notifications
You must be signed in to change notification settings - Fork 0
/
239.滑动窗口最大值.cpp
60 lines (51 loc) · 1.03 KB
/
239.滑动窗口最大值.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* @lc app=leetcode.cn id=239 lang=cpp
*
* [239] 滑动窗口最大值
*/
// @lc code=start
#include<vector>
#include<algorithm>
#include<iostream>
#include<deque>
using namespace std;
class MonotonicQueue{
public: deque<int> data;
void push(int n)
{
while(!data.empty() && data.back() < n){
data.pop_back();
}
data.push_back(n);
}
int max(){
return data.front();
}
void pop(int n)
{
if(!data.empty() && data.front() == n)
{
data.pop_front();
}
}
};
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MonotonicQueue window;
vector<int> res;
for(int i=0;i<nums.size();i++)
{
if(i<k-1)
{
window.push(nums[i]);
}else{
window.push(nums[i]);
res.push_back(window.max());
window.pop(nums[i-k+1]);
}
}
return res;
}
};
// @lc code=end