-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00239-sliding_window_maximum.cpp
More file actions
52 lines (37 loc) · 1000 Bytes
/
00239-sliding_window_maximum.cpp
File metadata and controls
52 lines (37 loc) · 1000 Bytes
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
// 239: Sliding Window Maximum
// https://leetcode.com/problems/sliding-window-maximum/
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
class Solution {
public:
// SOLUTION
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq;
vector<int> result;
int i=0, j=0;
while (j < nums.size()) {
while (!dq.empty() && nums[dq.back()]<nums[j])
dq.pop_back();
dq.push_back(j);
if (i > dq.front()) dq.pop_front();
if (j+1 >= k) {
result.push_back(nums[dq.front()]);
i++;
}
j++;
}
return result;
}
};
int main() {
Solution o;
// INPUT
vector<int> nums = {1,3,-1,-3,5,3,6,7};
int k = 3;
// OUTPUT
auto result = o.maxSlidingWindow(nums, k);
cout<<"["; for (auto v : result) cout<<v<<" "; cout<<"\b]"<<endl;
return 0;
}