一:暴力法
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size) {
ArrayList<Integer> res = new ArrayList<>();
if(num.length==0||size>num.length||size==0){
return res;
}
for(int i = 0;i<num.length-size+1;i++){
res.add(findmax(num,i,i+size));
}
return res;
}
private int findmax(int [] num,int start,int end){
int max = num[start];
for(int i=start;i<end;i++){
if(num[i]>max){
max = num[i];
}
}
return max;
}
}
二、双端队列
/**
* 思路:
* 1、双端队列保存滑动窗口的最大值(保存在头部),次大值数据
* 2、窗口滑动,从右侧遍历,比当前值小的移出队列,队首元素过期 移出队列,
* 当前元素的索引加入队列
*/
public ArrayList<Integer> maxInWindowsII(int [] num, int size) {
ArrayList<Integer> res = new ArrayList<>();
if (num == null || size <= 0 || num.length < size) {
return res;
}
// 使用双端队列 缓存滑动窗口,最大值保存在头部
ArrayDeque<Integer> queue = new ArrayDeque<>();
int len = num.length;
for (int i=0; i<len; i++){
// 从后面依次弹出队列中比当前num值小的元素,同时也能保证队列首元素为当前窗口最大值下标
while(!queue.isEmpty() && num[queue.peekLast()]<=num[i]) {
queue.pollLast();
}
// 当队首元素坐标对应的num不在窗口中,需要弹出
if(!queue.isEmpty() && i-queue.peekFirst()+1>size) {
queue.pollFirst();
}
// 把每次滑动的num下标加入队列
queue.offerLast(i);
// 当滑动窗口首地址i大于等于size时才开始写入窗口最大值
if(i+1 >= size) {
res.add(num[queue.peekFirst()]);
}
}
return res;
}
}