给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def maxInWindows(self, num, size): 4 n=len(num) 5 stack=[] 6 ans=[] 7 if size == 0: 8 return [] 9 for i in range(n): 10 while stack and num[i]>num[stack[-1]]: 11 stack.pop() 12 while stack and i-stack[0]>=size: 13 stack.pop(0) 14 stack.append(i) 15 if i>=size-1: 16 ans.append(num[stack[0]]) 17 return ans 18 # write code here