Title description
Given an array and the size of the sliding window, find the maximum value of all sliding windows. For example, if the input array {2,3,4,2,6,2,5,1} and the sliding window size 3, then there are 6 sliding windows in total, and their maximum values are {4,4,6, 6,6,5}; There are 6 sliding windows for the array {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}, {2,3,4,2,6,[2,5, 1]}.
Idea analysis
It is mainly solved by recursion and double pointers.
Code
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
int len = -1;//窗口长度
int start = 0;//开始处
int end = 0;//结束处
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
if(num == null||num.length<size||size == 0){
return list;
}
start = 0;//滑动窗口的开始
end = size-1;//滑动窗口的结束
len = size;
maxInWindowsHelper(num,start,end);
return list;
}
public void maxInWindowsHelper(int[] num,int start,int end){
if(end<num.length){
int max = -1;
for(int i = start; i<=end;i++){
//通过循环获得每一次的最大值
if(num[i]>max){
max = num[i];
}
}
list.add(max);
//找到了最大值,开始滑动,并开始下一次的递归
start = start+1;
end = end+1;
maxInWindowsHelper(num,start,end);
}
}
}