zoukankan      html  css  js  c++  java
  • 生成窗口最大数组

    题目

    有一个整形数组arr和一个大小为w的窗口从数组的最左边滑到最右边,窗口每次向右边滑一个位置。
      例如:数组为[4,3,5,4,3,3,6,7],窗口大小为3时:

    [4,3,5],4,3,3,6,7 5
    4,[3,5,4],3,3,6,7 5
    4,3,[5,4,3],3,6,7 5
    4,3,5,[4,3,3],6,7 4
    4,3,5,4,[3,3,6],7 6
    4,3,5,4,3,[3,6,7] 7

    实现思路

    使用淘汰劣势元素的方式进行实现,每个元素有位置和值两个属性,使用队列进行存储,处理原则:

    • 新加入的元素,使用值较大的优势,可以淘汰已存储在队列中比他小的元素。
    • 新加入的元素,无法淘汰队列中比其大的元素,但新加入的元素有位置优势,那么就需要排在大元素之后。
    • 每次移动窗口,队头不在窗口范围内,需要淘汰。

    使用上面的思路进行实现,那么每次移动窗口,队头的元素就是对大的值了。

    实现代码

    package com.github.zhanyongzhi.interview.algorithm.stacklist;
    
    import java.util.ArrayList;
    import java.util.Deque;
    import java.util.LinkedList;
    import java.util.List;
    
    /**
     * 获取各个窗口的最大值
     */
    public class GetWindowMax {
        public List<Integer> getWindowMax(Integer[] input, int windowSize) {
            Deque<Integer> maxIndexQueue = new LinkedList<Integer>();
            List<Integer> result = new ArrayList<>();
    
            for (int i = 0; i < input.length; i++) {
                if(maxIndexQueue.isEmpty()) {
                    maxIndexQueue.push(i);
                    continue;
                }
    
                //移除过期的索引
                if(maxIndexQueue.peekFirst() + 3 <= i)
                    maxIndexQueue.removeFirst();
    
                //当前如果是最大的数,则删除前面比其小的数字的索引,否则直接加到最后
                Integer lastElement = input[maxIndexQueue.peekLast()];
                Integer curElement = input[i];
    
                while(curElement >= lastElement){
                    maxIndexQueue.removeLast();
    
                    if(maxIndexQueue.isEmpty())
                        break;
    
                    lastElement = input[maxIndexQueue.peekLast()];
                }
    
                maxIndexQueue.addLast(i);
    
                //索引未够window size,不需要获取最大值
                if(i < (windowSize - 1))
                    continue;
    
                //最大值为开头的数字
                result.add(input[maxIndexQueue.peekFirst()]);
            }
    
            return result;
        }
    }
    

    在github中查看

  • 相关阅读:
    Spring Cloud Eureka的学习
    Maven环境配置
    Maven解决静态资源过滤问题
    Linux Desktop Entry文件配置解析
    iptables规则持久化
    Markdown学习总结
    输vim /etc/rc.d/init.d/mysqld 报错 …..localdomain.pid
    UE4 集成讯飞听写插件
    单机梦幻西游
    使用A*寻路小记
  • 原文地址:https://www.cnblogs.com/xiaohunshi/p/5720471.html
Copyright © 2011-2022 走看看