剑指Offer(栈和队列)-滑动窗口的最大值

  (滑动窗口的最大值)题目描述:


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


  解决思路:利用一个大顶堆

import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
        //大顶堆,从大到小的排列
        private PriorityQueue<Integer> heap=new PriorityQueue<Integer>(15,new Comparator<Integer>(){
            @Override
            public int compare(Integer o1,Integer o2){
                return o2-o1;
            }
        });
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
       //存放结果集
        ArrayList<Integer> result=new ArrayList<Integer>();
        if(num==null||num.length==0||num.length<size||size<=0){
            return result;
        }
        for(int i=0;i<size;i++){
            heap.offer(num[i]);
        }
        result.add(heap.peek());
        //i从1到num.length-size
        for(int i=1;i<num.length+1-size;i++){
            heap.remove(num[i-1]);
            heap.offer(num[i+size-1]);
            result.add(heap.peek());
        }
        return result;
    }
}

  解决办法二:

import java.util.ArrayList;
public class Solution {
 
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(num == null||size == 0 ||size>num.length){
            return result;
        }
 
        int max = num[0];//记录最大值
        int index = -1;//记录最大值下标,防止最大值过期
        int len = num.length;
        int plow = 0,phight = size-1;//滑动窗口边界
        while(phight<len){//此处不要条件plow<phight,因为有可能size=1
            if((index>=plow)&&(index<=phight)){//保证最大值未过期
                if(max<num[phight]){
                max = num[phight];
                index = phight;
                }
            }else{
                max = num[plow];
                index = plow;
                for(int i=plow;i<=phight;i++){
                    if(max<num[i]){
                        max = num[i];
                        index = i;
                    }
                }
            }
            result.add(max);
            plow++;
            phight++;
 
        }
        return result;
 
    }
}

  

原文地址:https://www.cnblogs.com/dashenaichicha/p/12540226.html