-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathSliding_Window_Maximum.cpp
65 lines (53 loc) · 1.62 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
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> result;
if(nums.size() < 1) return result;
unordered_map<int, int> freq;
set<int> numSet;
for(int i = 0; i < k; i++) {
freq[nums[i]]++;
numSet.insert(nums[i]);
}
auto max = --numSet.end();
result.push_back(*max);
for(int i = k; i < nums.size(); i++) {
freq[nums[i]]++;
numSet.insert(nums[i]);
freq[nums[i - k]]--;
if(freq[nums[i - k]] == 0) {
numSet.erase(nums[i - k]);
}
auto max = --numSet.end();
result.push_back(*max);
}
return result;
}
};
// using deque
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> result;
if(nums.size() < 1) return result;
deque <int> Q(k);
for(int i = 0; i < k; ++i) {
while(!Q.empty() and nums[i] >= nums[Q.back()]) {
Q.pop_back();
}
Q.push_back(i);
}
for(int i = k; i < nums.size(); ++i) {
result.push_back(nums[Q.front()]);
while(!Q.empty() and Q.front() <= i - k) {
Q.pop_front();
}
while(!Q.empty() and nums[i] >= nums[Q.back()]) {
Q.pop_back();
}
Q.push_back(i);
}
result.push_back(nums[Q.front()]);
return result;
}
};