利用优先队列 【0】列存储比较数值 【1】列存储索引数值 ,将队列peek的【1】列索引值进行判断是否最大值在滑动窗口中 ,如果在优先队列中则比较peek处数值找出滑动窗口的最大值;如果不在,永久移除该数据 ,使用当前滑动窗口的最大值。
public class leet239 {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
int[] result = new int[n-k+1];
PriorityQueue<int[]> priorityQueue = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0]!=o2[0]?o2[0]-o1[0] :o2[1]-o2[1];
}
});
for (int i = 0; i < k; i++) {
priorityQueue.offer(new int[]{nums[i],i});
}
result[0] = priorityQueue.peek()[0];
for (int i = k; i < n; i++) {
priorityQueue.offer(new int[]{nums[i],i});
while(priorityQueue.peek()[1]<=i-k){
priorityQueue.poll();
}
result[i-k+1] = priorityQueue.peek()[0];
}
return result;
}
public static void main(String[] args) {
int[] nums = {1,3,-1,-3,5,3,6,7};
leet239 solutinn = new leet239();
System.out.println(Arrays.toString(solutinn.maxSlidingWindow(nums, 3)));
}
}