239. 滑动窗口最大值
This commit is contained in:
30
test011.cpp
30
test011.cpp
@@ -1,4 +1,4 @@
|
|||||||
// 1.优先队列
|
// 方法一、优先队列
|
||||||
class Solution {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
|
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
|
||||||
@@ -19,4 +19,30 @@ public:
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
//
|
// 方法二、单调队列
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
|
||||||
|
int n = nums.size();
|
||||||
|
deque<int> q;
|
||||||
|
vector<int> ans;
|
||||||
|
for(int i = 0; i < k; i++){
|
||||||
|
while(!q.empty() && nums[i] >= nums[q.back()]){
|
||||||
|
q.pop_back();
|
||||||
|
}
|
||||||
|
q.push_back(i);
|
||||||
|
}
|
||||||
|
ans.push_back(nums[q.front()]);
|
||||||
|
for(int i = k; i < n; i++){
|
||||||
|
while(!q.empty() && nums[i] >= nums[q.back()]){
|
||||||
|
q.pop_back();
|
||||||
|
}
|
||||||
|
q.push_back(i);
|
||||||
|
while(q.front() <= i - k){
|
||||||
|
q.pop_front();
|
||||||
|
}
|
||||||
|
ans.push_back(nums[q.front()]);
|
||||||
|
}
|
||||||
|
return ans;
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user