滑动窗口最大值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 from deq indexes of all elements 17 # which are smaller than current element nums[i] 18 while deq and nums[i] > nums[deq[-1]]: 19 deq.pop() 20 21 # init deque and output 22 deq = deque() 23 max_idx = 0 24 for i in range(k): 25 clean_deque(i) 26 deq.append(i) 27 # compute max in nums[:k] 28 if nums[i] > nums[max_idx]: 29 max_idx = i 30 output = [nums[max_idx]] 31 32 # build output 33 for i in range(k, n): 34 clean_deque(i) 35 deq.append(i) 36 output.append(nums[deq[0]]) 37 return output
复杂度分析
时间复杂度:O(N),每个元素被处理两次- 其索引被添加到双向队列中和被双向队列删除。
空间复杂度:O(N),输出数组使用了O(N−k+1) 空间,双向队列使用了O(k)。
2020-01-08 20:53:02