https://leetcode-cn.com/problems/sliding-window-maximum/
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> q;
vector<int> res;
if(nums.size() ==0 ||k>nums.size()) return res;
//初始化前第一个窗口
for (int i = 0; i < k; i++) {
while (!q.empty()&& nums[i]>nums[q.back()])
{
q.pop_back();
}
q.push_back(i);
}
//初始化前第一个窗口
res.push_back(nums[q.front()]);
//开始滑动
for (int j = k; j < nums.size(); j++) {
//判断队列中最大值所对应的元素是否在当前窗口里;如果不在当前窗口内就把它移出队列
if (!q.empty()&&j - q.front() >= k) {
q.pop_front();
}
while (!q.empty()&&nums[j]> nums[q.back()])
{
q.pop_back();
}
q.push_back(j);
res.push_back(nums[q.front()]);
}
return res;
}
};
网友评论