生成窗口最大值数组

1、题目

参考书:程序员代码面试指南 IT名企算法与数据结构题目最优解
在这里插入图片描述在这里插入图片描述

2、解答

在这里插入图片描述

3、代码

public class 生成窗口最大值数组 {

    public static int[] getMaxWindow(int[] arr, int w) {

        if (arr.length < w || arr == null || w < 0) {
            return null;
        }
        if (w == 1) {
            return arr;
        }
        LinkedList<Integer> qmax = new LinkedList<>();
        int[] res = new int[arr.length - w + 1];
        int index = 0;
        /**
         * 1、如果qmax为空,i存入qmax
         * 2、如果qmax不为空,取qmax队尾存放的下标,记为j
         *    2.1、如果arr[j]>arr[i],把i存到队尾;
         *    2.2、如果arr[j]<=arr[i],把j从qmax弹出。
         */
        for (int i = 0; i < arr.length; i++) {
            while (!qmax.isEmpty() && arr[qmax.peekLast()] <= arr[i]) {
                qmax.pollLast();//检索并移除此列表的最后一个元素,或者如果此列表为空,则返回null。
            }
            qmax.addLast(i);//将指定元素追加在此列表的末尾。
            /** 如果对头下标 == i-w 说明队头下标已过期 **/
            if (qmax.peekFirst() == i - w) {//检索但不删除此列表的第一个元素,如果此列表为空,则返回null。
                qmax.pollFirst();//检索并移除此列表的第一个元素,或者如果此列表为空,则返回null。
            }
            if (i >= w - 1) {//i>2
                res[index] = arr[qmax.peekFirst()];
                index++;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {4, 3, 5, 4, 3, 3, 6, 7};
        int w = 3;
        int[] res = getMaxWindow(arr, w);
        for (Integer r : res) {
            System.out.print(r + " ");
        }
        System.out.println();
        test(arr);
    }

    /**
     * public E peek():检索但不删除此列表的头部(第一个元素)。
     * public E peekFirst():检索但不删除此列表的第一个元素,如果此列表为空,则返回null。
     * public E peekLast():检索但不删除此列表的最后一个元素,如果此列表为空,则返回null。
     */
    public static void test(int[] arr) {
        LinkedList<Integer> qmax = new LinkedList<>();
        for (Integer r : arr) {
            qmax.add(r);
        }
        for (int i = 0; i < 10; i++) {
            System.out.print(qmax.peekFirst() + " ");
            System.out.print(qmax.peekLast() + " ");
        }
    }
}

码云

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值