首页 > 其他分享 >239. 滑动窗口最大值

239. 滑动窗口最大值

时间:2023-03-16 12:00:24浏览次数:36  
标签:heapq nums int 最大值 索引 while 239 滑动 append

题目描述

滑动窗口的长度是k,每次右移一位,需要返回窗口中的最大值

f1-单调队列

基本分析

  1. 维护值还是索引?索引可以判断队头是否离开,是更好的选择
  2. 0-k-1的窗口怎么维护?只是执行while弹出队尾+追加i的操作,不考虑删除队头
  3. k-n-1的遍历中注意什么?队尾中弹出<nums[i]的索引;追加i;while弹出滑动出去的队头;追加答案。

代码

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        q = deque()

        ans = []
        for i in range(k):
            while q and nums[i] > nums[q[-1]]:
                q.pop()
            q.append(i)
        ans.append(nums[q[0]])

        for i in range(k, n):
            while q and nums[i] > nums[q[-1]]:
                q.pop()
            q.append(i)
            while q[0] <= i - k:
                q.popleft()
            ans.append(nums[q[0]])
        
        return ans

总结

  1. 为什么判断索引和i-k的关系?结尾是i,长度是k时,开始索引是i-k+1
f2-优先队列

基本分析

  1. 还有什么方法能维护区间内的最大值?优先队列
  2. 怎么保证队列的头在始终是在区间内的?队里面放值-索引的元组,不断查看队头索引和i-k的关系

代码

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        q = [(-nums[i], i) for i in range(k)]
        heapq.heapify(q)
        ans = []
        ans.append(-q[0][0])

        for i in range(k, n):
            heapq.heappush(q, (-nums[i], i))
            while q[0][1] <= i - k:
                heapq.heappop(q)
            ans.append(-q[0][0])
        
        return ans

总结

  1. python默认是小根堆,为了实现大根堆怎么办?把值转化为负的存取
  2. 堆的一些基本操作?heapq.heapify(q), heapq.heappush(q, (-nums[i], i)), heapq.heappop(q)
f3-分块+预处理
待补充

标签:heapq,nums,int,最大值,索引,while,239,滑动,append
From: https://www.cnblogs.com/zk-icewall/p/17222036.html

相关文章