滑动窗口的最大值

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

java:

 1 import java.util.*;
 2 public class Solution {
 3     public ArrayList<Integer> maxInWindows(int [] num, int size)
 4     {
 5         PriorityQueue<Integer> heap = new PriorityQueue<Integer>((o1,o2) -> o2-o1) ;
 6         ArrayList<Integer> res = new ArrayList<Integer>() ;
 7         if (num.length == 0 || size == 0 || num.length < size){
 8             return res ;
 9         }
10         for(int i = 0 ; i < size ; i++){
11             heap.add(num[i]) ;
12         }
13         res.add(heap.peek()) ;
14         for(int i = 0 , j = i + size ; j < num.length ; i++ , j++){
15             heap.remove(num[i]) ;
16             heap.add(num[j]) ;
17             res.add(heap.peek()) ;
18         }
19         return res ;
20     }
21 }
原文地址:https://www.cnblogs.com/mengchunchen/p/10583674.html