题目
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.
Follow up:
Could you solve it in linear time?
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
单调队列
这题直接用暴力法进行遍历是会超时的,可以考虑单调队列的思路。
队列是可以一端插入,另一端删除的数据结构,双端队列是可以同时在两边进行插入和删除的数据结构,利用双端队列实现单调队列。保持队列中的数据是递减的,即队首总是最大的元素,队尾元素最小,然后在遍历nums时,将当前元素nums[i]与队尾元素进行比较,如果队尾元素小于当前遍历元素,那么删除队尾,直至队列中呈现元素递减顺序。总是返回队列中的首元素,就可以得出结果。
python代码
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
if k<0 or k>n:
return []
res = []
window = []
for i in range(n):
if window and window[0]<=i-k:
window.pop(0)
while window and nums[window[-1]]<=nums[i]:
window.pop()
window.append(i)
if i>=k-1:
res.append(nums[window[0]])
return res
好久不刷题,感觉思路都看不懂了。