优先队列/单调队列 - 滑动窗口最大值
生活随笔
收集整理的這篇文章主要介紹了
优先队列/单调队列 - 滑动窗口最大值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接
優先隊列
class Solution { public:vector<int> maxSlidingWindow(vector<int>& nums, int k) {int n = nums.size();priority_queue<pair<int,int>> q;for (int i = 0; i < k; ++i) {q.emplace(nums[i], i);}vector<int> ret = {q.top().first};for (int i = k; i < n; ++i) {q.emplace(nums[i], i);while (q.top().second <= i - k) {q.pop();}ret.push_back(q.top().first);}return ret;} }; class Solution:def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:n = len(nums)# Python 默認的優先隊列是小根堆q = [(-nums[i], i) for i in range(k)]heapq.heapify(q)ans = [-q[0][0]]for i in range(k, n):heapq.heappush(q, (-nums[i], i))while (q[0][1] <= i - k):heapq.heappop(q)ans.append(-q[0][0])return ans雙向列表
class Solution { public:vector<int> maxSlidingWindow(vector<int>& nums, int k) {deque<int> q;vector<int> ret;int n = nums.size();for (int i = 0; i < n; ++i) {while (!q.empty() && nums[q.back()] <= nums[i]) {q.pop_back();}q.push_back(i);if (q.front() <= i - k) {q.pop_front();}if (i >= k - 1) {ret.push_back(nums[q.front()]);}}return ret;} }; class Solution:def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:n = len(nums)q = collections.deque()for i in range(k):while q and nums[i] >= nums[q[-1]]:q.pop()q.append(i)ans = [nums[q[0]]]for i in range(k, n):while q and nums[i] >= nums[q[-1]]:q.pop()q.append(i)while q[0] <= i - k:q.popleft()ans.append(nums[q[0]])return ans總結
以上是生活随笔為你收集整理的优先队列/单调队列 - 滑动窗口最大值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 动态规划/贪心 - 无重叠区间
- 下一篇: 并查集 - 除法求值