首页 > 编程语言 > 详细

[LeetCode in Python] 239 (H) sliding window maximum 滑动窗口最大值

时间:2020-05-03 16:35:50      阅读:57      评论:0      收藏:0      [点我收藏+]

题目

https://leetcode-cn.com/problems/sliding-window-maximum/

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

进阶:

你能在线性时间复杂度内解决此题吗?

示例:

输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]

解释:

滑动窗口的位置 最大值


[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

提示:

1 <= nums.length <= 10^5
-10^4?<= nums[i]?<= 10^4
1 <= k?<= nums.length

解题思路

  • 单调队列:队列中元素从头到尾是单调下降的。
  • 在追加新元素时需从尾向头遍历,将小于新元素的都出队,由此维持队列的单调性。
  • 扫描输入的数组时,当窗口满了,就要开始检查窗口左边缘是否是单调队列的最大值,如果是,需要将其出队。

代码

class MonotonicQueue(object):
    def __init__(self):
        self._q = collections.deque()

    def push(self, e):
        # - pop all elements if < e
        while self._q and self._q[-1] < e:
            self._q.pop()

        self._q.append(e)

    def pop(self):
        # - pop the max element
        return self._q.popleft()

    def get_max(self):
        return self._q[0]

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        res = []
        mq = MonotonicQueue()
        for i,n in enumerate(nums):
            mq.push(n)

            # - if window is full
            if i >= k-1:
                res.append(mq.get_max())

                # - if left edge of window is the max value
                if nums[i-k+1] == mq.get_max():
                    mq.pop()
                    
        return res

[LeetCode in Python] 239 (H) sliding window maximum 滑动窗口最大值

原文:https://www.cnblogs.com/journeyonmyway/p/12821970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!