64-滑动窗⼝的最⼤值
题⽬描述
给定⼀个数组和滑动窗⼝的⼤⼩,找出所有滑动窗⼝⾥数值的最⼤值。例如,如果输⼊数组 {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]} 。 窗⼝⼤于数组⻓度的时候,返回空。
思路及解答
⾸先进⾏⾮空判断,以及数组⻓度是否不为 0 ,是否不⼩于窗⼝⻓度。
其次,使⽤⼀个双向链表,⾥⾯保存的是索引,遍历每⼀个元素,如果双向队列不为空且最后的元素作为索引的数值⼩于当前的元素,就把当前的元素的索引加到队列的后⾯。(这样可以保证队列从头到尾是单调递减的,也就是队尾的元素就是最⼩的元素)。
然后把当前的元素加进去队列尾部。判断队列前⾯的元素是不是索引位置不符合,如果不符合,就移除队列头部的元素。
那么此时的队列⾸部肯定就是滑动窗⼝的最⼤值。(此处应该判断滑动窗⼝⽣效的索引)
以 2, 3, 4, 2, 6, 2, 5, 1 为例:




所有的窗⼝最⼤值⾄此已经收集完成。
public class Solution64 {
public static void main(String[] args) {
int[] nums = {2, 3, 4, 2, 6, 2, 5, 1};
System.out.println(new Solution64().maxInWindows(nums, 3));
}
public ArrayList<Integer> maxInWindows(int[] num, int size) {
ArrayList<Integer> results = new ArrayList<>();
if (num == null || num.length == 0 || num.length < size || size <= 0) {
return results;
}
LinkedList<Integer> integers = new LinkedList<>();
for (int i = 0; i < num.length; i++) {
while (!integers.isEmpty() && num[integers.peekLast()] < num[i]) {
integers.removeLast();
}
integers.addLast(i);
while (i - integers.peekFirst() >= size) {
integers.removeFirst();
}
if (i >= size - 1) {
results.add(num[integers.peekFirst()]);
}
}
return results;
}
}- 时间复杂度:O(n),所有的元素都进⼊队列,再出队列
- 空间复杂度:O(n),使⽤额外的队列空间存储索引以及窗⼝最⼤值。
