题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。
package 数组;
//1.循环;2,队列
import java.util.ArrayList;
public class 滑动窗口的最大值 {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer>list=new ArrayList<>();
if(num.length==0||size==0) return list;
for (int i = 0; i <=num.length-size; i++) {
int max=num[i];
for (int j = i+1; j < i+size; j++) {
if(num[j]>max) max=num[j];
}
list.add(max);
}
return list;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
滑动窗口的最大值 A=new 滑动窗口的最大值();
int []num= {1,3,5,7,9,11,13,15};
System.out.println(A.maxInWindows(num,4));
}
}