1,题目要求
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input:nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output:[3,3,5,5,6,7]
Explanation:
Window position | Max |
---|---|
[1 3 -1] -3 5 3 6 7 | 3 |
1 [3 -1 -3] 5 3 6 7 | 3 |
1 3 [-1 -3 5] 3 6 7 | 5 |
1 3 -1 [-3 5 3] 6 7 | 5 |
1 3 -1 -3 [5 3 6] 7 | 6 |
1 3 -1 -3 5 [3 6 7] | 7 |
Note:
You may assume k is always valid, 1 ≤ k ≤ input array’s size for non-empty array.
Follow up:
Could you solve it in linear time?
给定一个数组nums,有一个大小为k的滑动窗口,它从数组的最左边移动到最右边。 您只能在窗口中看到k编号。 每次滑动窗口向右移动一个位置。 返回最大滑动窗口。
2,题目思路
对于这道题,题目是将一个长度为k的滑动窗口从最左滑到最有,分别找到每个窗口下的最大值。
滑动窗口问题并不新鲜,关键点在于滑动过程中值的变化。
这一题是要求求出对应每个窗口下的最大值,最简单的办法是分别求出每个窗口内的最大值即可。不过这种方法的时间复杂度过高。
如果想在线性的时间复杂度内解决这个问题,就需要在滑动窗口的同时,对当前窗口的最大值进行一个动态的更新。
由于数组的无序性,滑动过程最大值的变化是不确定的,因此,在这里,我们使用单调队列来解决这个问题。
所谓单调队列(monotone queue),是这样一种东西,给你一个队列,让你在队尾添加元素,在队首删除元素,时刻维护队列中的最大值,使其查询时间为O(1)。
着这里,我们使用双端队列deque——可以在队列的两端实现插入和删除操作。
让该队列的队首元素始终是当前窗口的最大值的索引,且队列的长度始终≤k。
在这个队列中,从两端删除元素:
- 从队首删除元素:因为长度超了,必须删掉当前最左的元素。
- 从队尾删除元素:新的nums[i]的值比当前队尾所指的nums[mq.back()]大,需要进行更新。
这样,队列内部的顺序与元素在nums的相对顺序一样,且它们所表示的nums的值,也是从大到小的。
这样,我们就可以解决这一问题了。
3,代码实现
static const auto s = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
//使用一个双端队列,来实现一个单调队列
//队首存储当前值最大的数字的idx
//始终维持其长度≤k
deque<int> mq;
vector<int> res;
for(int i = 0;i<nums.size();i++){
//长度超了,删除最左元素
if(!mq.empty() && mq.front() == i-k)
mq.pop_front();
//始终保持队列内部索引有序、且对应的nums的值从大到小
while(!mq.empty() && nums[mq.back()] < nums[i])
mq.pop_back();
mq.push_back(i);
if(i >= k-1)
res.push_back(nums[mq.front()]);
}
return res;
}
};