-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsliding_window_maximum.cpp
More file actions
58 lines (54 loc) · 1.37 KB
/
sliding_window_maximum.cpp
File metadata and controls
58 lines (54 loc) · 1.37 KB
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
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
/**
* Describe: Given an array of number and a window with size k, the window
* slides from left to right, find maximum value at the window at each sliding.
*/
class Solution {
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
deque<int> q(k);
int len = nums.size();
vector<int> rst;
for (int i = 0; i < k; ++i) {
while (!q.empty() && nums[q.back()] <= nums[i]) {
q.pop_back();
}
q.push_back(i);
}
for (int i = k; i < len; ++i) {
rst.push_back(nums[q.front()]);
while (!q.empty() && q.front() <= i - k) {
q.pop_front();
}
while (!q.empty() && nums[q.back()] <= nums[i]) {
q.pop_back();
}
q.push_back(i);
}
if (!nums.empty()) {
rst.push_back(nums[q.front()]);
}
return rst;
}
};
int main() {
Solution so;
vector<int> test;
int n, k;
while (cin >> n) {
cin >> k;
test = vector<int>(n);
for (auto& ele : test) {
cin >> ele;
}
auto re = so.maxSlidingWindow(test, k);
for (auto ele : re) {
cout << ele << " ";
}
cout << endl;
}
return 0;
}