滑动窗口的最大值
题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。
分析
- 求指定范围数据的最大值,可以借助大顶堆实现。每次滑动,分别出入一个。堆顶即是最大值。
- 也可以使用一个双端队列。第一个位置保存当前窗口最大值,滑动时判断当前最大值是否过期。对于新增的值从队尾比较,比其小的值丢掉。
实现
实现1
public class Solution {
// 大顶堆
public PriorityQueue<Integer> maxQueue = new PriorityQueue<Integer>((o1,o2)->o2-o1);
public ArrayList<Integer> result = new ArrayList<Integer>();
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
if(num == null || num.length <= 0 || size <= 0 || size > num.length){
return result;
}
int count=0;
// 初始化滑动窗口
for(;count<size;count++){
maxQueue.offer(num[count]);
}
// 每次滑动,找到最大值,出入堆一个
while(count < num.length){
result.add(maxQueue.peek());
maxQueue.remove(num[count-size]);
maxQueue.add(num[count]);
count++;
}
// 保存结果
result.add(maxQueue.peek());
return result;
}
}
实现2
public ArrayList<Integer> maxInWindows(int [] num, int size){
if (num == null || num.length == 0 || size <= 0 || num.length < size) {
return new ArrayList<Integer>();
}
ArrayList<Integer> result = new ArrayList<>();
//双端队列,用来记录每个窗口的最大值下标
LinkedList<Integer> qmax = new LinkedList<>();
int index = 0;
for (int i = 0; i < num.length; i++) {
while (!qmax.isEmpty() && num[qmax.peekLast()] < num[i]) {
qmax.pollLast();
}
qmax.addLast(i);
//判断队首元素是否过期
if (qmax.peekFirst() == i - size) {
qmax.pollFirst();
}
//向result列表中加入元素
if (i >= size - 1) {
result.add(num[qmax.peekFirst()]);
}
}
return result;
}