-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathSliding Window Maximum.cpp
48 lines (36 loc) · 1.14 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
/*
Solution by Rahul Surana
***********************************************************
You are given an array of integers nums, there is a sliding window of size k
which is moving from the very left of the array to the very right.
You can only see the k numbers in the window.
Each time the sliding window moves right by one position.
Return the max sliding window.
***********************************************************
*/
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
queue<int> q;
multiset<int> s;
vector<int> ans;
for(auto x: nums){
if(q.size() >= k-1){
int a = q.front();
if(q.size()>=k){
q.pop();
s.erase(s.find(a));
}
q.push(x);
s.insert(x);
// if(s.size()>=0)
ans.push_back(*(s.rbegin()));
}
else{
q.push(x);
s.insert(x);
}
}
return ans;
}
};