标签:problems pre ref ble turn solution 滑动 size 最大
单调队列分为递增队列和递减队列,一般用来求某个固定长度(例如:滑动窗口的最值)序列中的最大/最小值。
对于递增队列,队首元素就是最小值。
对于递减队列,队首元素就是最大值。
1.递增队列(队列首尾最小值)
if(q.empty()) q.push_back(A[i]); else if(q.back()>A[i]){ while((!q.empty())&&q.back()>A[i]){ q.pop_back(); } q.push_back(A[i]); } else q.push_back(A[i]);
2.递减队列(队列首尾最大值)
if(q.empty()) q.push_back(A[i]); else if(q.back()<A[i]){ while((!q.empty())&&q.back()<A[i]){ q.pop_back(); } q.push_back(A[i]); } else q.push_back(A[i]);
示例:
求滑动窗口的最大值,题目链接 https://leetcode.com/problems/sliding-window-maximum/
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { deque<int> dp; vector<int> ans; for (int i=0; i<nums.size(); i++) { while(!dp.empty() && dp.back() < nums[i])dp.pop_back(); dp.push_back(nums[i]); if (i >= k - 1) { ans.push_back(dp.front()); // 此窗口的最大值加入到返回值中 if (nums[i - k + 1] == dp.front())dp.pop_front(); // 如果滑动窗口移动一次将队首元素移动出去了 } } return ans; } };
标签:problems pre ref ble turn solution 滑动 size 最大
原文地址:https://www.cnblogs.com/qiang-wei/p/12286876.html