-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSliding_Window_Maximum.cpp
More file actions
41 lines (40 loc) · 1.08 KB
/
Sliding_Window_Maximum.cpp
File metadata and controls
41 lines (40 loc) · 1.08 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
class Solution {//O(nlog(k))
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
map<int,int> count;
int n = nums.size();
for(int i=0; i<min(n,k);i++){
count[nums[i]]++;
}
vector<int> res;
res.push_back(count.rbegin()->first);
for(int i = k; i<n; i++){
count[nums[i-k]]--;
count[nums[i]]++;
if(count[nums[i-k]]==0)
count.erase(nums[i-k]);
res.push_back(count.rbegin()->first);
}
return res;
}
};
class Solution {//O(n)
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq;
int n = nums.size();
vector<int> res;
for(int i=0; i<n; i++){
if(i>=k){
if(dq.front()==nums[i-k])
dq.pop_front();
}
while(!dq.empty() && dq.back()<nums[i])
dq.pop_back();
dq.push_back(nums[i]);
if(i>=k-1)
res.push_back(dq.front());
}
return res;
}
};