• 《程序员代码面试指南》第一章 栈和队列 生成窗口最大值数组


    题目

    有一个整形数组arr,一个大小为 w 的窗口从数组最左边滑到最右边,每次移动一个位置,输出在每个窗口下的窗口最大值
    

    java代码

    /**
     * @Description:生成窗口最大值
     * @Author: lizhouwei
     * @CreateDate: 2018/4/5 20:38
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter1_7 {
    
        public int[] getMaxWindow(int[] arr, int w) {
            if (arr == null || arr.length < 1) {
                return new int[]{0};
            }
            //存放最终结果
            int length = arr.length;
            //比如 length =4,w=3, 则有两个窗口最大值
            int[] res = new int[length - w + 1];
            int index = 0;
            //存放数组的索引
            LinkedList<Integer> qmax = new LinkedList<Integer>();
            //循环数组
            for (int i = 0; i < arr.length; i++) {
                while (!qmax.isEmpty() && arr[qmax.peekLast()] < arr[i]) {
                    qmax.pollLast();
                }
                qmax.offerLast(i);
                //如果 qmax中第一个存放的索引失效,则删除,比如 i=5,w=3,则 5-3=2 索引2和2之前的都是失效的
                if (qmax.peekFirst() <= i - w) {
                    qmax.pollFirst();
                }
                //最大值结果是从 i>=w-1开始的记录的,例如 i=1 ,w=3 ,3-1=2, 此时还未到第一个窗口
                if (i >= w - 1) {
                    res[index++] = arr[qmax.peekFirst()];
                }
            }
            return res;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter1_7 chapter = new Chapter1_7();
            int[] arr = {4, 3, 5, 4, 3, 3, 6, 7};
            int[] res = chapter.getMaxWindow(arr, 3);
            for (int i : res) {
                System.out.print(i + "  ");
            }
        }
    }
    
  • 相关阅读:
    Webfunny Js错误分析讲解
    Webfunny漏斗分析功能讲解
    Webfunny自定义埋点功能讲解
    Webfunny连线用户功能讲解
    Webfunny用户细查功能讲解
    C语言打印数字前补0
    github上新晋star3K的开源AI模型,包含情感分析等
    IT系统架构的演化
    微服务架构与SOA架构的区别与联系
    开源的分布式事务-Seata的设计原理
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8724462.html
Copyright © 2020-2023  润新知