leetcode 239: Sliding Window Maximum

本文详细介绍了如何使用双端队列(deque)来解决滑动窗口内的最大值问题,通过移除旧元素并添加新元素保持队列的单调递减特性,确保每次窗口移动后都能快速获取当前窗口的最大值。

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

Use the a deque to save numbers like a waitlist. If the window size equals to k, start the pop operation of the deque and push the front number into the res vector. If nums[i-k] equals to the front number of deque, the front should be popped because the window moves. Then a new number nums[i] should be pushed from back of the deque. While pushing, all numbers at the back of the deque which are smaller than nums[i] should be removed because they came earlier than nums[i] and if they are moved out of the window later, all numbers that are bigger than them are still in the deque, so the maximum number won't be affected.

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> res;
        deque<int> waitlist;
        int n=nums.size();
        int i=0;
        while(i<n)
        {
            if(i>=k&&nums[i-k]==waitlist.front())
                waitlist.pop_front();
            while(!waitlist.empty()&&nums[i]>waitlist.back())
                waitlist.pop_back();
            waitlist.push_back(nums[i]);
            i++;
            if(i>=k)
                res.push_back(waitlist.front());
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值