import java.util.ArrayDeque;
import java.util.ArrayList;
/**
* 题目:滑动窗口的最大值。 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
* 例如,如果输入数组{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)定义两个指针作为滑动窗口两端,向右滑动,每次遍历窗口内所有数将最大值存入ArrayList,时间复杂度较高。
* 2)用一个双端队列,队列第一个位置保存当前窗口的最大值,当窗口滑动一次 1.判断当前最大值是否过期2.新增加的值从队尾开始比较,把所有比他小的值丢掉
*
* @author hexiaoli
*/
public class Main {
public static ArrayList<Integer> maxInWindows1(int[] num, int size) {
// 结果声明
ArrayList<Integer> result = new ArrayList<>();
// 边界
if (size <= 0 || num.length < size || num == null) {
return result;
}
// 设置头尾指针
int head = 0;
int tail = size - 1;
// 向右滑动窗口
for (int i = 0; i <= num.length - size; i++) {
int max = Integer.MIN_VALUE;
// 遍历窗口中的所有数取出最大值
for (int j = head; j <= tail; j++) {
if (max < num[j]) {
max = num[j];
}
}
result.add(max);
// 首尾指针移动
head++;
tail++;
}
return result;
}
public static ArrayList<Integer> maxInWindows2(int[] num, int size) {
// 结果声明
ArrayList<Integer> result = new ArrayList<>();
// 边界
if (size <= 0 || num.length < size || num == null) {
return result;
}
// 设置头尾指针
int head;
// 声明一个双端队列,记录位置
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
// 遍历数组
for (int i = 0; i < num.length; i++) {
// 开始位置
head = i - size + 1;
// 如果为空的话则加入,判断当前最大值是否过期
if (q.isEmpty()) {
q.offer(i);
} else if (head > q.peekFirst()) {
q.pollFirst();
}
//循环移出队列中比当前值小的值。
while ((!q.isEmpty()) && num[q.peekLast()] <= num[i]) {
q.pollLast();
}
q.offer(i);
//记录结果
if (head >= 0)
result.add(num[q.peekFirst()]);
}
// 返回结果
return result;
}
public static void main(String[] args) {
int[] num = new int[] { 2, 3, 4, 2, 6, 2, 5, 1 };
// ArrayList<Integer> result = maxInWindows1(num, 3);
ArrayList<Integer> result = maxInWindows2(num, 3);
for (Integer integer : result) {
System.out.println(integer);
}
}
}