Leetcode239 滑动窗口最大值
链接:239. 滑动窗口最大值 - 力扣(LeetCode)
这道题是目前为止做过的第一个hard难度的题目,滑动窗口,有点类似我们之前做的找三个元素相加等于0的那道题,但是这道题 我们是用队列的思路去实现。
并且需要自己去实现一个单调队列。
为什么要自己去实现呢?
因为我们的首先要保证我们每个窗口都需要找到最大值,那我们这个队列可不可以每次只去维护我们的最大值?每一次的移动队列都会告诉我们当前窗口中的最大值
这个队列应该长这样子:
每次窗口移动,直接调用queue.pop()移除元素值,queue.push添加元素的值
然后queue.front返回我们的最大值
but,没有!哈哈哈哈所以只能我们自己实现了
所以我们的队列是不是应该把最大值放在最前面呢?答案是肯定的,并且队列的元素是要按照从大到小排序的,才能保证我们的front函数每次去取到最大值。
代码:
#
# @lc app=leetcode.cn id=239 lang=python3
#
# [239] 滑动窗口最大值
#
# https://leetcode.cn/problems/sliding-window-maximum/description/
#
# algorithms
# Hard (50.04%)
# Likes: 1927
# Dislikes: 0
# Total Accepted: 370.2K
# Total Submissions: 740.6K
# Testcase Example: '[1,3,-1,-3,5,3,6,7]\n3'
#
# 给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k
# 个数字。滑动窗口每次只向右移动一位。
#
# 返回 滑动窗口中的最大值 。
#
#
#
# 示例 1:
#
#
# 输入: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
#
#
# 示例 2:
#
#
# 输入:nums = [1], k = 1
# 输出:[1]
#
#
#
#
# 提示:
#
#
# 1 <= nums.length <= 10^5
# -10^4 <= nums[i] <= 10^4
# 1 <= k <= nums.length
#
#
#
# @lc code=start
class Myqueue:
def __init__(self):
self.queue = []
def pop(self,value):
if self.queue and value==self.queue[0]:
self.queue.pop(0)
def push(self,value):
while self.queue and value > self.queue[-1]:
self.queue.pop()
self.queue.append(value)
def front(self):
return self.queue[0]
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
queue = Myqueue()
res = []
if k==0:
return None
for i in range(k):
queue.push(nums[i])
res.append(queue.front())#记录当前 前k个元素的最大值
for i in range(k,len(nums)):
queue.pop(nums[i-k])#弹出前端开头元素
queue.push(nums[i])#继续加入后面元素
res.append(queue.front())#继续添加最大值
return res
# @lc code=end
总结:
最近在加强栈和队列的使用,平常很多题型如果当我们用数组或者指针的方式不能做的时候,可以考虑栈和队列这种数据结构