【leetcode】- 239. Sliding Window Maximum滑动窗口最大值 python版

滑动窗口最大值

题目

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Follow up:
Could you solve it in linear time?

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]

Explanation:

Window position ------------------ Max

[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

单调队列

这题直接用暴力法进行遍历是会超时的,可以考虑单调队列的思路。
队列是可以一端插入,另一端删除的数据结构,双端队列是可以同时在两边进行插入和删除的数据结构,利用双端队列实现单调队列。保持队列中的数据是递减的,即队首总是最大的元素,队尾元素最小,然后在遍历nums时,将当前元素nums[i]与队尾元素进行比较,如果队尾元素小于当前遍历元素,那么删除队尾,直至队列中呈现元素递减顺序。总是返回队列中的首元素,就可以得出结果。

python代码

class Solution:
   def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
       n = len(nums)
       if k<0 or k>n:
           return []
       res = []
       window = []
       for i in range(n):
           if window and window[0]<=i-k:
               window.pop(0)
           while window and nums[window[-1]]<=nums[i]:
               window.pop()
           window.append(i)
           if i>=k-1:
               res.append(nums[window[0]])
       return res

好久不刷题,感觉思路都看不懂了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值