64.滑动窗口的最大值
题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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 not num:
return None
if size <= 0:
return []
head = 0
tail = size
res = []
while tail <= len(num):
l = num[head:tail]
l.sort()
res.append(l[size - 1])
head += 1
tail += 1
return res
方法二:
用一个双端队列,队列第一个位置保存当前窗口的最大值,当窗口滑动一次
1.判断当前最大值是否过期
2.新增加的值从队尾开始比较,把所有比他小的值丢掉
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# write code here
#队列中存储的是num中元素的下标
queue = []
res = []
i = 0
while size > 0 and i < len(num):
#当前最大值是否过期:队首元素坐标对应的num不在窗口中,需要弹出
if len(queue) > 0 and (i - size + 1)> queue[0]:
queue.pop(0)
#新增加的值从队尾开始比较,把所有比他小的值丢掉,保证队列首元素为当前窗口最大值下标
while len(queue) > 0 and num[queue[-1]] < num[i]:
queue.pop()
queue.append(i) #把每次滑动的num下标加入队列
#//当滑动窗口首地址i大于等于size时才开始写入窗口最大值
if i >= size - 1:
res.append(num[queue[0]])
i += 1
return res