-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path239. Sliding Window Maximum.cpp
69 lines (40 loc) · 1.18 KB
/
239. Sliding Window Maximum.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
60
61
62
63
64
65
66
67
68
69
// Monotonic Queue datastructure
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
if(nums.empty())
return res;
deque<int> window; // store indices
for(int i = 0; i<nums.size(); ++i) {
while(!window.empty() && window.front() < i-k+1)
window.pop_front();
while(!window.empty() && nums[window.back()] < nums[i])
window.pop_back();
window.push_back(i);
if (i >= k-1)
res.push_back(nums[window.front()]);
}
return res;
}
};
-----------------------
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
if(nums.empty())
return res;
multiset<int> window;
for(int i = 0; i<nums.size(); ++i) {
window.insert(nums[i]);
while(window.size() > k) {
window.erase(window.find(nums[i-k]));
}
if (window.size() == k) {
res.push_back(*window.rbegin());
}
}
return res;
}
};