zoukankan      html  css  js  c++  java
  • [LeetCode in Python] 239 (H) sliding window maximum 滑动窗口最大值

    题目

    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
    
  • 相关阅读:
    python2.7学习记录之三
    编程题
    解题的小问题(C++)
    算法入门(C++)
    逻辑回归
    入门级(python)
    python2.7学习记录之二
    sql语句-排序后加入序号再运算判断取想要的项
    linux中c多线程同步方法
    进程间的通讯方式
  • 原文地址:https://www.cnblogs.com/journeyonmyway/p/12821970.html
Copyright © 2011-2022 走看看