[Leetcode] 239. Sliding Window Maximum 解题报告

本文介绍了一种求解滑动窗口最大值的问题,并提供了两种高效算法:使用大顶堆和双边队列的方法。通过这两种方式,可以在O(n log n)和O(n)的时间复杂度内解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note: 
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

思路

1、利用大顶堆:我们知道大顶堆可以保证最开始的元素是最大的,所以在本题目中,我们维护一个大顶堆。每遍历到一个数,首先调整大顶堆,使得开头元素最大,然后判断最大值知否还在k窗口之内,如果不在,就迭代删除,直到最大元素仍然在k窗口之内。如果窗口大小已经达到了k,就添加当前的最大元素到结果集中。由于调整大顶堆的时间复杂度是O(logn),所以本算法的时间复杂度是O(nlogn)。

2、利用双边队列:还有一种更巧妙的解法就是利用双边队列。我们在双边队列中维护一个递减序列,也就是说,当遍历到一个新数之后,我们从双边队列的尾部开始,删除所有小于等于它的数,然后将该数加入到双边队列的尾部。这种处理方法可以保证双边队列中的数一定是单调递减的,当前最大数一定位于双边队列的首位。这样当窗口足够大的时候,我们直接将队列首位元素加入结果集中即可。当然在遍历的过程中,不要忘了更新队列。在代码实现中,为了方便更新队列,我们在双边队列中存储的是最大数的在数组中的索引,而不是具体值。该算法的时间复杂度是O(n)。在分析的过程中我们发现,虽然在for循环内部还有while循环,但是采用均摊分析可知,数组中的每个数最多入队列一次,出队列一次。

代码

1、利用大顶堆:

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<pair<int, int>> windows;
        vector<int> ret;
        for(int i = 0; i < nums.size(); ++i) {
            windows.push_back(make_pair(nums[i], i));
            push_heap(windows.begin(), windows.end());
            while(i - windows[0].second >= k) {
                pop_heap(windows.begin(), windows.end());
                windows.pop_back();
            }
            if(i + 1 >= k) {
                ret.push_back(windows[0].first);
            }
        }
        return ret;
    }
};

2、利用双边队列:

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> ret;
        if(nums.size() == 0 || k == 0) {
            return ret;
        }
        deque<int> que;     // only stores the indices
        for(int i = 0; i < nums.size(); ++i) {
            while(!que.empty() && nums[i] >= nums[que.back()]) {
                que.pop_back();
            }
            que.push_back(i);
            if(i >= que.front() + k) {
                que.pop_front();
            }
            if(i >= k - 1) {
                ret.push_back(nums[que.front()]);
            }
        }
        return ret;
    }
};
内容概要:本书《Deep Reinforcement Learning with Guaranteed Performance》探讨了基于李雅普诺夫方法的深度强化学习及其在非线性系统最优控制中的应用。书中提出了一种近似最优自适应控制方法,结合泰勒展开、神经网络、估计器设计及滑模控制思想,解决了不同场景下的跟踪控制问题。该方法不仅保证了性能指标的渐近收敛,还确保了跟踪误差的渐近收敛至零。此外,书中还涉及了执行器饱和、冗余解析等问题,并提出了新的冗余解析方法,验证了所提方法的有效性和优越性。 适合人群:研究生及以上学历的研究人员,特别是从事自适应/最优控制、机器人学和动态神经网络领域的学术界和工业界研究人员。 使用场景及目标:①研究非线性系统的最优控制问题,特别是在存在输入约束和系统动力学的情况下;②解决带有参数不确定性的线性和非线性系统的跟踪控制问题;③探索基于李雅普诺夫方法的深度强化学习在非线性系统控制中的应用;④设计和验证针对冗余机械臂的新型冗余解析方法。 其他说明:本书分为七章,每章内容相对独立,便于读者理解。书中不仅提供了理论分析,还通过实际应用(如欠驱动船舶、冗余机械臂)验证了所提方法的有效性。此外,作者鼓励读者通过仿真和实验进一步验证书中提出的理论和技术。
### LeetCode Top 100 Problems with Java Solutions and Explanations LeetCode serves as an essential resource for developers aiming to enhance skills through solving algorithmic challenges[^1]. For individuals seeking guidance specifically on popular questions using Java, several resources provide comprehensive coverage. A notable approach involves focusing on dynamic programming, arrays, strings, trees, graphs, backtracking, depth-first search (DFS), breadth-first search (BFS), heaps, binary indexed tree, segment tree, bit manipulation, union find, two pointers, sliding window, greedy algorithms, divide & conquer among others. Each category has representative problems that frequently appear within the top 100 list: #### Example Problem: Maximum Subarray One classic example from this collection is **Maximum Subarray**, which can be efficiently solved via Kadane's Algorithm. Herein lies its implementation along with explanation: ```java class Solution { public int maxSubArray(int[] nums) { int n = nums.length; int max = Integer.MIN_VALUE, sum = 0; for (int i = 0; i < n; i++) { sum += nums[i]; max = Math.max(sum, max); if (sum < 0) sum = 0; } return max; } } ``` The logic behind this solution revolves around maintaining a running total (`sum`) while iterating over elements. Whenever `sum` drops below zero, resetting it ensures only positive contributions towards potential maximum subarrays are considered[^5]. To explore more such problems systematically, one might refer to curated lists available online or repositories dedicated to documenting solutions like those found at specific project addresses[^2]. These often include detailed analyses alongside code snippets tailored primarily toward enhancing comprehension beyond mere functionality.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值