方法一:暴力解法,遍历即可
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> list=new ArrayList<Integer>();
if(size>num.length||size==0){
return list;
}
for(int i=0;i<num.length-size+1;i++){
int max=num[i];
for(int j=i;j<i+size;j++){
max=Math.max(max,num[j]);
}
list.add(max);
}
return list;
}
}
方法二:定义一个双向队列用来存放数组中元素的下标。先将下标0放入队列,然后从下标1的位置开始遍历,每遍历一个值都将队列中小于这个值的元素去掉。然后将这个值的下标放入队列。如果当前遍历到的i减去队列头大于等于size,说明这个下标过期了需要被排除。如果遍历到的i+1大于等于size了,说明这个窗口应该滑动了,先将队列头元素放入list中。然后继续遍历。
注意:滑动窗口的大小为1的时候,num元素直接复制到list中并返回即可。
import java.util.*;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> list=new ArrayList<Integer>();
LinkedList<Integer> queue=new LinkedList<Integer>();
queue.add(0);
if(size>num.length||size==0){
return list;
}
if(size==1){
for(int i:num){
list.add(i);
}
return list;
}
for(int i=1;i<num.length;i++){
int value=num[i];
if(value>num[queue.peekLast()]);
{
while(!queue.isEmpty()&&value>num[queue.peekLast()]){
queue.pollLast();
}
}
queue.add(i);
if(i-queue.peek()>=size){
queue.poll();
}
if(i+1>=size){
list.add(num[queue.peek()]);
}
}
return list;
}
}