From ba4fe4c9a00b053fa70483a1540e8e7d38f3b316 Mon Sep 17 00:00:00 2001 From: xingyou wu <3050128610@qq.com> Date: Sat, 13 Sep 2025 23:15:44 +0800 Subject: [PATCH] =?UTF-8?q?239.=20=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test011.cpp | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/test011.cpp b/test011.cpp index 10e6c72..efae9fe 100644 --- a/test011.cpp +++ b/test011.cpp @@ -1,4 +1,4 @@ -// 1.优先队列 +// 方法一、优先队列 class Solution { public: vector maxSlidingWindow(vector& nums, int k) { @@ -19,4 +19,30 @@ public: } }; -// \ No newline at end of file +// 方法二、单调队列 +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + int n = nums.size(); + deque q; + vector ans; + for(int i = 0; i < k; i++){ + while(!q.empty() && nums[i] >= nums[q.back()]){ + q.pop_back(); + } + q.push_back(i); + } + ans.push_back(nums[q.front()]); + for(int i = k; i < n; i++){ + while(!q.empty() && nums[i] >= nums[q.back()]){ + q.pop_back(); + } + q.push_back(i); + while(q.front() <= i - k){ + q.pop_front(); + } + ans.push_back(nums[q.front()]); + } + return ans; + } +}; \ No newline at end of file