滑动窗口的最大值 牛客网 剑指Offer

mac2022-06-30  120

滑动窗口的最大值 牛客网 剑指Offer

题目描述给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]} class Solution: def maxInWindows(self, num, size): if not num or size <= 0: return [] deque = [] last_max_index = -1 if len(num) >= size: for i in range(len(num)-size+1): if last_max_index >= i: v = num[i+size-1] if v >= num[last_max_index]: last_max_index = i+size-1 deque.append(num[last_max_index]) else: max_value = num[i] for j in range(1,size): v = num[i+j] if v > max_value: max_value = v last_max_index = i+j deque.append(max_value) return deque def maxInWindows2(self, num, size): if not num or size <= 0: return [] deque = [] if len(num) >= size: for i in range(len(num)-size+1): max_value = num[i] for j in range(1,size): v = num[i+j] if v > max_value: max_value = v last_max_index = i+j deque.append(max_value) return deque

 

转载于:https://www.cnblogs.com/vercont/p/10210361.html

最新回复(0)