题解 | #滑动窗口的最大值#
滑动窗口的最大值
http://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788
import java.util.*;
//利用堆的方法解决,大根堆堆顶是滑动窗口的最大值
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size) {
if(size > num.length || size == 0){
return new ArrayList();
}
//引入Compactor形成大根堆
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
ArrayList<Integer> resList = new ArrayList<Integer>();
int left = 0;
int right = size;
for(int i = 0; i < size; i++){
heap.add(num[i]);
}
while(right < num.length){
resList.add(heap.peek());
heap.remove(num[left++]);
heap.add(num[right++]);
}
resList.add(heap.peek());
return resList;
}
}