[编程题]滑动窗口的最大值
滑动窗口的最大值
http://www.nowcoder.com/questionTerminal/1624bc35a45c42c0bc17d17fa0cba788
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; } }