forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsliding-window-maximum.cpp
40 lines (34 loc) · 990 Bytes
/
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
// Time: O(n)
// Space: O(k)
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: The maximum number inside the window at each moving.
*/
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
const int n = nums.size();
deque<int> q;
vector<int> max_numbers;
for (int i = 0; i < k; ++i) {
while (!q.empty() && nums[i] >= nums[q.back()]) {
q.pop_back();
}
q.emplace_back(i);
}
for (int i = k; i < n; ++i) {
max_numbers.emplace_back(nums[q.front()]);
while (!q.empty() && nums[i] >= nums[q.back()]) {
q.pop_back();
}
while (!q.empty() && q.front() <= i - k) {
q.pop_front();
}
q.emplace_back(i);
}
if (!q.empty()) {
max_numbers.emplace_back(nums[q.front()]);
}
return max_numbers;
}
};