题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
python实现:
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# write code here
#队列+栈==>双端队列
n = len(num)
if n < size or size<=0:
return []
from collections import deque
queue = deque([])
result = []
for i in range(n):
while queue and num[queue[-1]] <= num[i]:
queue.pop()
queue.append(i)
#看是否有数字划出窗口的左端
if queue[0] < i-size+1:
queue.popleft()
if size<=i+1:
result.append(num[queue[0]])
return result