滑动窗口最大值
- 题解1 优先队列(大顶堆)(双循环没过)
-
- 题解2 单调队列deque(设计同labuladong)
-
题解1 优先队列(大顶堆)(双循环没过)
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
for(int i = 0; i < nums.size()-k+1; i++){
priority_queue<int> heapqueue;
for(int j = i; j < i+k; j++)
heapqueue.push(nums[j]);
res.push_back(heapqueue.top());
}
return res;
}
};
改进后
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
priority_queue<pair<int, int>> heapque;
for(int i=0; i < k-1; i++){
heapque.emplace(nums[i], i);
}
for(int i = k-1; i < nums.size(); i++){
heapque.emplace(nums[i], i);
while(heapque.top().second <= i-k)
heapque.pop();
res.push_back(heapque.top().first);
}
return res;
}
};
题解2 单调队列deque(设计同labuladong)
class Solution {
public:
class Myqueue{
deque<int> q;
public:
void push(int n){
while(! q.empty() && q.back() < n){
q.pop_back();
}
q.push_back(n);
}
int max(){
return q.front();
}
void pop(int n){
if(n == q.front())
q.pop_front();
}
};
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
Myqueue Que;
for(int i = 0; i < nums.size(); i++){
if(i < k-1){
Que.push(nums[i]);
}else{
Que.push(nums[i]);
res.push_back(Que.max());
Que.pop(nums[i-k+1]);
}
}
return res;
}
};
标准题解(同接雨水,deque存下标)
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int n = nums.size();
deque<int> q;
for (int i = 0; i < k; ++i) {
while (!q.empty() && nums[i] >= nums[q.back()]) {
q.pop_back();
}
q.push_back(i);
}
vector<int> ans = {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;
}
};