给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。 窗口大于数组长度的时候,返回空
这题同leetcode 239题,但是这次尝试了上一题用到的最大堆,非常方便,也可以用LinkedList或者Deque等,把最大放在最前,理论和堆一样,务必记住最大堆用PriorityQueue实现的方式
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> ans = new ArrayList<>();
if(num.length == 0 || size == 0) return ans;
if(size > num.length) return ans;
PriorityQueue<Integer> maxheap = new PriorityQueue<>(new Comparator<Integer>(){
//@override
public int compare(Integer o1, Integer o2){
return o2.compareTo(o1);
}
});
for(int i = 0; i < size; i++){
maxheap.offer(num[i]);
}
ans.add(maxheap.peek());
int l = 0, r = size;
while(r < num.length){
if(num[l] == maxheap.peek()) maxheap.poll();
maxheap.offer(num[r]);
l++;
r++;
ans.add(maxheap.peek());
}
return ans;
}
}