题目:
给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
deque<int> temp;
if(nums.empty())
{
return res;
}
for(int i=0;i<nums.size();i++)
{
if(!temp.empty()&&temp.front()==i-k)
{
temp.pop_front();
}
while(!temp.empty()&&nums[i]>nums[temp.back()])
{
temp.pop_back();
}
temp.push_back(i);
if(i-k+1>=0)
{
res.push_back(nums[temp.front()]);
}
}
return res;
}
};
1.变量的最前端(也就是 temp.front())是此次遍历的最大值的下标
2.当我们遇到新的数时,将新的数和双项队列的末尾(也就是temp.back())比较,如果末尾比新数小,则把末尾扔掉,直到该队列的末尾比新数大或者队列为空的时候才停止,做法有点像使用栈进行括号匹配。
3.双项队列中的所有值都要在窗口范围内