From ce67219141fbe62377facafe1024a81a3ad3eb85 Mon Sep 17 00:00:00 2001 From: hzs Date: Wed, 11 Nov 2020 16:03:43 +0800 Subject: [PATCH 1/2] =?UTF-8?q?[239.=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=80=BC]=20[Python]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 数据结构系列/单调队列.md | 50 +++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/数据结构系列/单调队列.md b/数据结构系列/单调队列.md index eb298a1..41b494f 100644 --- a/数据结构系列/单调队列.md +++ b/数据结构系列/单调队列.md @@ -210,4 +210,52 @@ vector maxSlidingWindow(vector& nums, int k) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +python3版本 + +```python +from collections import deque + +class MonotonicQueue(object): + def __init__(self): + # 双端队列 + self.data = deque() + + def push(self, n): + # 实现单调队列的push方法 + while self.data and self.data[-1] < n: + self.data.pop() + self.data.append(n) + + def max(self): + # 取得单调队列中的最大值 + return self.data[0] + + def pop(self, n): + # 实现单调队列的pop方法 + if self.data and self.data[0] == n: + self.data.popleft() + + +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + # 单调队列实现的窗口 + window = MonotonicQueue() + + # 结果 + res = [] + + for i in range(0, len(nums)): + + if i < k-1: + # 先填满窗口前k-1 + window.push(nums[i]) + else: + # 窗口向前滑动 + window.push(nums[i]) + res.append(window.max()) + window.pop(nums[i-k+1]) + return res + +``` \ No newline at end of file From c786b6ab43c7c24e55b4877ea6c1afafae1a2179 Mon Sep 17 00:00:00 2001 From: hzs Date: Wed, 11 Nov 2020 16:19:53 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E3=80=90239.=E6=BB=91=E5=8A=A8=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC=E3=80=91=E3=80=90Python?= =?UTF-8?q?=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 数据结构系列/单调队列.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/数据结构系列/单调队列.md b/数据结构系列/单调队列.md index 41b494f..094e510 100644 --- a/数据结构系列/单调队列.md +++ b/数据结构系列/单调队列.md @@ -210,10 +210,14 @@ vector maxSlidingWindow(vector& nums, int k) {

+ ======其他语言代码====== python3版本 +由[SCUHZS](ttps://github.com/brucecat)提供 + + ```python from collections import deque