题解 | #滑动窗口的最大值#
滑动窗口的最大值
https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size) {
ArrayList<Integer> res = new ArrayList<>();
if (num == null) return res;
int len = num.length;
if (len == 0 || len < size || size == 0) return res;
int maxNum = Integer.MIN_VALUE;
for (int i = 0; i < len - size + 1; ++i) {
if (i == 0) {
for (int j = i; j < size; ++j) {
maxNum = Math.max(maxNum, num[j]);
}
} else {
if (num[i + size - 1] > maxNum) maxNum = num[i + size - 1];
else if (num[i - 1] == maxNum) {
maxNum = Integer.MIN_VALUE;
for (int j = i; j < size + i; ++j) {
maxNum = Math.max(maxNum, num[j]);
}
}
}
res.add(maxNum);
}
return res;
}
}
当窗口从下标 0 开始时需要遍历一次窗口大小来寻找最大值,而在此后可以判断当前最大值和所要添加值之间的大小以及判断即将离开窗口的值是否等于当前的最大值,然后再去判断是否需要再次遍历寻找最大值。

查看3道真题和解析