给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[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
提示:
你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。
进阶:
你能在线性时间复杂度内解决此题吗?
以前写过一次了,链接 ,这次用python和重写c++
python: 就是换了种语言,别的地方没改
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res = []
q = []
for i,num in enumerate(nums):
if q and i - q[0] + 1 > k: q.pop(0)
while q and num > nums[q[-1]]: q.pop()
q.append(i)
if q and i >= k - 1: res.append(nums[q[0]])
return res
c++
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int hh = 0, tt = -1; //队首,队尾
int q[nums.size() + 10];
vector<int> res;
for(int i = 0; i < nums.size(); ++i)
{
if (hh <= tt && i - k + 1 > q[hh]) ++hh;
while(hh <= tt && nums[i] >= nums[q[tt]]) --tt; //Ⅰ
q[++tt] = i; //Ⅱ
if (hh <= tt && i >= k - 1) res.push_back(nums[q[hh]]); //Ⅲ
}
return res;
}
};
注意一下ⅠⅡⅢ的顺序问题
如果ⅢⅠⅡ这样排列,那么会导致插入的数不是最大值
[1,2,0,5]
3 到20(5未插入)这里判断Ⅰ之前,q中是12,如果这时执行Ⅲ那么将插入nums[1] = 2是错误的
如果ⅠⅢⅡ这样排列,会导致数据排空,将不插入值
[1,2,0,5]
3 到20(5未插入),先执行Ⅲ,则q为空,所以将不会更新答案