题目描述
解法
设置队列,保证第一位一直是最大并且属于该滑动窗口的
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
deque = collections.deque()
n = len(nums)
res = []
if len(nums) == 0:
return []
for i in range(min(k,len(nums))):
while deque and deque[-1]< nums[i]:
deque.pop()
deque.append(nums[i])
res.append(deque[0])
for i in range(k,n):
if deque[0] == nums[i-k]:
deque.popleft()
while deque and deque[-1]< nums[i]:
deque.pop()
deque.append(nums[i])
res.append(deque[0])
return res