题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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:
思路2:数组切片
Python
# -*- coding:utf-8 -*- class Solution: def maxInWindows(self, num, size): # write code here if len(num) < size or size == 0: return [] # 思路1 # left, right = 0, size-1 # res = [] # while right < len(num): # maxindex = left # for j in range(left+1,right+1): # if num[j] > num[maxindex]: # maxindex = j # res.append(num[maxindex]) # left += 1 # right += 1 # return res # 思路2 res = [] for i in range(len(num)-size+1): res.append(max(num[i:i+size])) return res if __name__ == '__main__': result = Solution().maxInWindows([2,3,4,2,6,2,5,1],3) print(result)
作者:huangqiancun
出处:http://www.cnblogs.com/huangqiancun/
本博客若无特殊说明则由作者原创发布,欢迎转载,但请注明出处 :)