From 97c4d1baec4789f7fe8aa656b459fc63509548a7 Mon Sep 17 00:00:00 2001 From: Lane Zhang Date: Tue, 22 Oct 2024 10:22:27 +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=E6=96=B0=E8=A7=A3=E6=B3=95=EF=BC=9A=E7=94=A8?= =?UTF-8?q?"=E5=A0=86=E6=8E=92=E5=BA=8F"=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 23bf615b..2db1942a 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -339,6 +339,32 @@ class Solution: return result ``` +#### 新解法:用"堆排序"实现 +* 时间复杂度:`O(n * log(n))`, 比`单调队列`解法要慢。 + +```python +import heapq + + +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + results = [] + num_index_list = [] # 将用“堆排序”对它进行排序,元素为 (num, index) 元组 + + for i in range(len(nums)): + # 把 nums[i] 值取负数,最大的就到最小,合乎 Python 堆排序从小到大的规则。 + # 还要把 index (i) 存入,因为通过 i 可知道对应的 num 何时不能再被使用(num 已经处在左侧窗口的更左边) + heapq.heappush(num_index_list, (-nums[i], i)) + # num_index_list[0]是最小值所在 tuple;'<= i - k' 表示 num 已经处在左侧窗口的更左边 + while num_index_list[0][1] <= i - k: # while 表示所有过气 num 都要丢弃 + heapq.heappop(num_index_list) # 丢弃最小值 + + if i >= k - 1: + results.append(-num_index_list[0][0]) # 第一个就是最小值,负最小值就是最大值,加入结果集 + + return results +``` + ### Go: ```go