From fba159b1356bf4fe55658c05090b1b3ae7956e10 Mon Sep 17 00:00:00 2001 From: Lane Zhang Date: Tue, 22 Oct 2024 09:20:21 +0800 Subject: [PATCH] =?UTF-8?q?0239.=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=80=BC.md=20=E5=8A=A0=E5=85=A5=20Python=20?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E8=A7=A3=E6=B3=95=E4=BA=8C=EF=BC=9A=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E7=94=A8=E5=8D=95=E8=B0=83=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 32 +++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 23bf615b..aae1b4d2 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -299,7 +299,7 @@ class Solution { ``` ### Python: - +#### 解法一:使用自定义的单调队列类 ```python from collections import deque @@ -339,6 +339,36 @@ class Solution: return result ``` +#### 解法二:直接用单调队列 +```python +from collections import deque + + +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + max_list = [] # 结果集合 + kept_nums = deque() # 单调队列 + + for i in range(len(nums)): + update_kept_nums(kept_nums, nums[i]) # 右侧新元素加入 + + if i >= k and nums[i - k] == kept_nums[0]: # 左侧旧元素如果等于单调队列头元素,需要移除头元素 + kept_nums.popleft() + + if i >= k - 1: + max_list.append(kept_nums[0]) + + return max_list + + +def update_kept_nums(kept_nums, num): # num 是新加入的元素 + # 所有小于新元素的队列尾部元素,在新元素出现后,都是没有价值的,都需要被移除 + while kept_nums and num > kept_nums[-1]: + kept_nums.pop() + + kept_nums.append(num) +``` + ### Go: ```go