LeetCode 剑指 Offer 59 - I. 滑动窗口的最大值

本文介绍了一种通过暴力解法及双端队列实现的滑动窗口最大值算法。暴力解法每次移动窗口都重新计算最大值;双端队列则维护一个按元素大小排序的队列并实时更新窗口内的最大值。

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

原题链接
思路:暴力解法和双端队列。
暴力解法:窗口每次移动都去找当前窗口内的最大值。
双端队列:存储元素的的下标,队列中下标的对应元素是从大到小的顺讯,并按时判断当前队列中的最大值是否还在窗口内。

暴力解法:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */


int maxInt(int* nums, int left, int numsSize){
    int max = -100000000;
    for(int i = 0; i < numsSize; i++){
        if(nums[left + i] > max) max = nums[left + i];
    }
    return max;
}

int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize){
    if(numsSize ==0 ){
        *returnSize = 0;
        return nums;
    }
    if(k == 1){
        *returnSize = numsSize;
        return nums;
    }
    *returnSize = numsSize - k + 1;
    int* arr = (int*)malloc(sizeof(int)*(numsSize - k + 1));
    for(int i = 0; i < numsSize - k + 1; i++){
        arr[i] = maxInt(nums, i, k);
    }
    return arr;
}

双端队列:

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> res
        deque<int> tem;     
        for(int i=0; i<nums.size(); ++i)
        {
            while(!tem.empty() && nums[i]>nums[tem.back()]) tem.pop_back();
            if(!tem.empty() && tem.front()<i-k+1) tem.pop_front();
            tem.push_back(i);
            if(i>=k-1)  res.push_back(nums[tem.front()]);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值