题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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:暴力
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def maxInWindows(self, nums, k): 4 # write code here 5 if not k or k>len(nums): 6 return [] 7 maxs = [max(nums[:k])] 8 for i in range(len(nums)-k): 9 maxs.append(max(nums[i+1:i+k+1])) 10 return maxs 11
运行时间:30ms
占用内存:5760k
法2:增加判断条件 参考网上
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def maxInWindows(self, nums, k): 4 # write code here 5 if not k or k>len(nums): 6 return [] 7 maxs = [max(nums[:k])] 8 curmax = maxs[0] 9 for i in range(len(nums)-k): 10 if curmax==nums[i]:#如果当前最大数字是窗口的首元素,那么下一个窗口的最大元素在后面 11 curmax = max(nums[i+1:i+k+1]) 12 elif curmax<nums[i+k]: #如果新的窗口的首元素大于当前当前窗口最大值,更新curmax 13 curmax = nums[i+k] 14 maxs.append(curmax) 15 return maxs 16
运行时间:26ms
占用内存:5640k
原文地址:https://www.cnblogs.com/zle1992/p/8312641.html
时间: 2024-10-13 04:04:34