题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。
解题思路
法一:简单的暴力法
法二:双向队列
用一个双向队列,队列第一个位置保存当前窗口的最大值,当窗口滑动一次,判断当前最大值是否过期(当前最大值的位置是不是在窗口之外),新增加的值从队尾开始比较,把所有比他小的值丢掉。这样时间复杂度为O(n)。
本题有两种解法如上,关于暴力解法思想如下,对于一个数组,滑动窗口从数组头部开始移动一直移动到尾部,记录下每次移动窗口中最大的值即可。数组num,窗口大小size,决定从前到后需要移动一共(num.length-size)次,每次窗口可覆盖size个数值,需要求出每次窗口中的最大值,方法利用index记录每次窗口移动后的第一个元素索引,将num[index]默认为最大值赋予temp变量,每次都将窗口中其余数值和num[index]对比,然后更新temp的值,即完成每个窗口最大值的查找!最后将每次求出的窗口最大值写在arraylist中去。
代码实现
去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片
.
import java.util.ArrayList;
public class maxInWindows {
//滑动窗口的最大值
public ArrayList<Integer> maxEleArray(int[] num,int size){
ArrayList<Integer> res=new ArrayList<>();
if (num.length<size||size==0){
return res;
}
for (int i=0;i<num.length-size+1;i++){
res.add(max(num,i,size));
}
return res;
}
public int max(int[] num,int index,int size){
int temp=num[index];
for (int i=index+1;i<index+size;i++){
if (num[i]>temp){
temp=num[i];
}
}
return temp;
}
// 双向队列
public ArrayList<Integer> maxInWindows2(int [] num, int size){
ArrayList<Integer> res = new ArrayList<Integer>(); // 结果
LinkedList<Integer> deque = new LinkedList<Integer>(); // 队列
if(num.length == 0 || size == 0)
return res;
for(int i = 0; i < num.length; i++){
if(!deque.isEmpty() && deque.peekFirst() <= i - size)
deque.poll();
while(!deque.isEmpty() && num[deque.peekLast()] < num[i])
deque.removeLast();
deque.offerLast(i);
if(i + 1 >= size)
res.add(num[deque.peekFirst()]);
}
return res;
}
public static void main(String[] args) {
maxInWindows test=new maxInWindows();
int[] num={2,3,4,2,6,2,5,1};
ArrayList<Integer> maxArray=test.maxEleArray(num,3);
System.out.println("最大值序列:"+maxArray);
}
}
总结
本题来源于面试经典教材《剑指offer》中 归属于栈&队列类型题目。
同许多在算法道路上不断前行的人一样,不断练习,修炼自己!
如有博客中存在的疑问或者建议,可以在下方留言一起交流,感谢各位!
最后,感谢AIAS!
到此栈&队列题目更新完毕,下面更新Heap&Hashmap!