LeetCode滑动窗口239

给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回滑动窗口中的最大值。

我的代码:

 1 class Solution:
 2     def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
 3         res = []
 4         dq = [] # 滑动窗口,存放索引
 5         if len(nums)<1 or k<1:
 6             return res
 7         for i in range(0,k,1): # 第一个窗口
 8             while len(dq) !=0 and nums[i]>nums[dq[-1]]: # 后面的大,前面肯定不是最大,应该删除
 9                 dq.pop(-1)
10             dq.append(i)
11         res.append(nums[dq[0]]) # 将第一个窗口最大值放入结果中
12         for j in range(k,len(nums),1):    
13             # nums[j]是否比前面大,删除尾部
14             while len(dq)!=0 and nums[j]>nums[dq[-1]]:
15                 dq = dq[0:-1]
16             # 前面是否超出窗口大小,是否应该滑出
17             if len(dq)!=0 and j-dq[0]>=k:
18                 dq = dq[1:]
19             dq.append(j)
20             res.append(nums[dq[0]])
21         return res
22         
23             
24 
25                 
26 
27         

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sliding-window-maximum

原文地址:https://www.cnblogs.com/shuangcao/p/13485470.html