题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。
简单的暴力方法,主要是注意一下切片位置:
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# write code here
if size>len(num) or not size:
return []
lens = len(num)
l,r = 0,size
res = []
while r<=lens:
res.append(max(num[l:r]))
l+=1
r+=1
return res
用一个辅助栈/队列 存当前窗口最大的一个数的方法:
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# write code here
if not num or not size:
return []
lens = len(num)
win_max = []
res = []
for i in range(lens):
#如果新来的数比较大就把之前的干掉,保持win_max[0]的位置数在窗口内最大
while win_max and num[i]>num[win_max[-1]]:
win_max.pop()
#存索引不存值,为了判断还是否在窗口内
win_max.append(i)
#即使[0]位置很大,但如果它不在窗口里了,就把它leftpop掉
while win_max and i-win_max[0]>size-1:
win_max.pop(0)
#形成窗口后开始加入结果
if i>=size-1:
res.append(num[win_max[0]])
return res