剑指offer65题(滑动窗口的最大值)

本文介绍了一种高效算法,用于解决寻找给定数组中所有滑动窗口的最大值问题。通过使用双端队列,该算法能动态维护窗口内最大值,并支持快速更新。文章详细解释了算法的工作原理及实现过程。

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

题目:给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。

思路

 * 思路:滑动窗口应当是队列,但为了得到滑动窗口的最大值,队列序可以从两端删除元素,因此使用双端队列。
 *     原则:
 *     对新来的元素k,将其与双端队列中的元素相比较
 *     1)前面比k小的,直接移出队列(因为不再可能成为后面滑动窗口的最大值了!),
 *     2)前面比k大的X,比较两者下标,判断X是否已不在窗口之内,不在了,直接移出队列
 *     队列的第一个元素是滑动窗口中的最大值
代码
import java.util.ArrayList;
import java.util.LinkedList;

public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer>  list = new ArrayList<Integer>();
        if(size > num.length || size<1 || num == null){
            return list;
        }
        //index放的是num中值对应的下标
        LinkedList<Integer> indexDeque = new LinkedList<Integer>();
        //第一个滑动窗口的最大值
        for(int i=0;i<size-1;i++){
            while (!indexDeque.isEmpty() && num[i]>num[indexDeque.getLast()]){
                indexDeque.removeLast();
            }
            indexDeque.addLast(i);
        }
        for (int i = size - 1; i < num.length; i++) {
        while (!indexDeque.isEmpty() && num[i] > num[indexDeque.getLast()]) {
            indexDeque.removeLast();
            }
        indexDeque.addLast(i);
        if (i - indexDeque.getFirst() + 1 > size) {
            indexDeque.removeFirst();
            }
            list.add(num[indexDeque.getFirst()]);
        }
        return list;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值