滑动窗口的最大值

来源:互联网 发布:大连理工软件学院几本 编辑:程序博客网 时间:2024/06/09 11:53

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。

分析:用一个链表list存储窗口移动过程中可能成为最大值的数字,

          当数字x大于前面的数字时,移除前面的数字,然后加入x,因为当x存在时前面的数字永远不会成为最大值。

          当数字y小于前面的数字时,如果前面的数字移除窗口,y有可能成为最大值 因此加入list中


   public ArrayList<Integer> maxInWindows(int [] num, int size)

    {  
 ArrayList<Integer> queue = new ArrayList<Integer>();
        /*保持当前窗口的最大值或有可能成为最大值队列*/
 ArrayList<Integer> list = new ArrayList<Integer>();
 if(num==null||num.length<=0||size<=0||size>num.length){//合法性检查
 return list;
 }
 queue.add(0);//队列里存储最大值下标
 int i=1;
 int len = size-num.length>0?num.length:size; //初始化窗口 选择size和length较小的一个
 while(i<len){
 while(!queue.isEmpty()&&num[i]>num[queue.get(queue.size()-1)]){
 queue.remove(queue.size()-1);/*在一个窗口下,如果新加入的数大于前面的数 将前面的值删除 因为前面的数无法
                  成为最大值*/
 }
 queue.add(i);
 i++;
 }
 list.add(num[queue.get(0)]);
 for(i=size;i<num.length;i++){
 while(!queue.isEmpty()&&num[i]>num[queue.get(queue.size()-1)]){
 queue.remove(queue.size()-1);
 }
 queue.add(i);
 while(i-queue.get(0)>=size){
 queue.remove(0);
 }
 list.add(num[queue.get(0)]);
 }
 return list;  

    }

题目来源:牛客网

0 0
原创粉丝点击