-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathSliding Window Maximum.cpp
119 lines (76 loc) · 1.99 KB
/
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.
Input :
a[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}
k = 3
Output :
3 3 4 5 5 5 6
*/
#include<iostream>
#include<queue>
using namespace std;
/*
solution1: whenever the window moves, calculate the maximal number in the window.
O(nk) time, O(1) space
*/
/*
solution2: use maximal heap to store k numbers.
O(nlogn) time, O(n) space
*/
typedef pair<int, int> Pair;
void MaxSlidingWindow2(int arr[], int len, int k, int window[]) {
priority_queue<Pair> Q;
for (int i = 0; i < k; ++i) {
Q.push(Pair(arr[i], i));
}
for (int i = k; i < len; ++i) {
Pair p = Q.top();
window[i-k] = p.first;
while (p.second <= i-k) {//pop the old elements not in new window
Q.pop();
p = Q.top();
}
Q.push(Pair(arr[i], i));
}
window[n-k] = Q.top().first;
}
/*
solution3:use deque to store k numbers.
O(n) time, O(k) space
*/
void MaxSlidingWindow3(int arr[], int len, int k, int window[]) {
deque<int> Q;
for (int i = 0; i < k; ++i) {
while (!Q.empty() && arr[i] >= arr[Q.back()]) { //elements in the deque decreases.
Q.pop_back();
}
Q.push_back(i);
}
for (int i = k; i < len; ++i) {
window[i-k] = arr[Q.front()];
while (!Q.empty() && arr[i] >= arr[Q.back()]) {
Q.pop_back();
}
while (!Q.empty() && Q.front() <= i-k) {//pop the old elements not in new window
Q.pop_front();
}
Q.push_back(i);
}
window[n-k] = arr[Q.front()];
}
int main() {
int a[9] = {1, 2, 3, 1, 4, 5, 2, 3, 6};
int b[7];
int c[7];
MaxSlidingWindow2(a,9,3,b);
MaxSlidingWindow3(a,9,3,c);
for(int i = 0; i < 7; ++i) {
cout<<b[i]<<" ";
}
cout<<endl;
for(int i = 0; i < 7; ++i) {
cout<<c[i]<<" ";
}
cout<<endl;
return 0;
}