滑动窗口最大值leetcode & nowcoder(python)
方法一:暴力 时间O(nk) 1 class Solution: 2 def maxInWindows(self, num, size): 3 # write code here 4 if len(num)*size == 0: 5 return [] 6 res=[] 7 for i in range(len(num)-size+1): 8 res.append(max(num[i:i+size])) 9 return res 方法二:双端队列 双端队列保存当前窗口的最大值 1 from collections import deque 2 class Solution: 3 def maxSlidingWindow(self, nums: 'List[int]', k: 'int') -> 'List[int]': 4 # base cases 5 n = len(nums) 6 if n * k == 0: 7 return [] 8 if k == 1: 9 return nums 10 11 def clean_deque(i): 12 # remove indexes of elements not from sliding window 13 if deq and deq[0] == i - k: 14 deq.popleft() 15 16 # remove