题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值.例如,如果输入数组 {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 -*-
class Solution:
def maxInWindows(self, nums, k):
# write code here
if not k or k>len(nums):
return []
maxs = [max(nums[:k])]
for i in range(len(nums)-k):
maxs.append(max(nums[i+1:i+k+1]))
return maxs
运行时间:30ms
占用内存:5760k
法 2: 增加判断条件 参考网上
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, nums, k):
# write code here
if not k or k>len(nums):
return []
maxs = [max(nums[:k])]
curmax = maxs[0]
for i in range(len(nums)-k):
if curmax==nums[i]:#如果当前最大数字是窗口的首元素,那么下一个窗口的最大元素在后面
curmax = max(nums[i+1:i+k+1])
elif curmax<nums[i+k]: #如果新的窗口的首元素大于当前当前窗口最大值,更新curmax
curmax = nums[i+k]
maxs.append(curmax)
return maxs
运行时间:26ms
占用内存:5640k
来源: http://www.bubuko.com/infodetail-2466312.html