用到了一个双端队列 LinkedList
package com.ryan.offer;
import java.util.ArrayList;
import java.util.LinkedList;
public class SlideWindow {
public static void main(String[] args) {
int[] arr= {1,3,5,7,9,11,13,15};
getCurrentWindowMaxValue(arr, 4);
System.out.println(getCurrentWindowMaxValue(arr, 3));
}
public static ArrayList<Integer> getCurrentWindowMaxValue(int[] arr, int size) {
if (arr == null || size < 1 || arr.length < size) {
return null;
}
ArrayList<Integer> list=new ArrayList<>();
LinkedList<Integer> qmax = new LinkedList<Integer>();
for(int i=0;i<arr.length;i++) {
if(qmax.isEmpty()) {
qmax.add(i);
}else {
while((!qmax.isEmpty()&&(arr[qmax.peekLast()]<=arr[i]))) {
qmax.pollLast();
}
qmax.addLast(i);
}
if((i>(size-1))&&(qmax.peekFirst()<(i-size+1))) {
qmax.pop();
}
if(i>=size-1) {
list.add(arr[qmax.peekFirst()]);
}
}
return list;
}
}
网友评论