有一个整型数组arr和一个大小为w的窗口从数组的最左边滑到最右边,窗口每次向右滑一个位置。
例如,数组为[4,3,5,4,3,3,6,7],窗口大小为3时:
[4 3 5] 4 3 3 6 7 窗口中最大值为5 4 [3 5 4] 3 3 6 7 窗口中最大值为5 4 3 [5 4 3] 3 6 7 窗口中最大值为5 4 3 5 [4 3 3] 6 7 窗口中最大值为4 4 3 5 4 [3 3 6] 7 窗口中最大值为6 4 3 5 4 3 [3 6 7] 窗口中最大值为7 若是数组长度为n,窗口大小为w,则一共产生n-w+1个窗口的最大值。
请实现一个函数。
java
package com.iqiyi;
import java.util.LinkedList;
public class Code1_7 {
public static void main(String[] args){
int[] arr=new int[]{4,3,5,4,3,3,6,7};
int[] ans=getMaxWindow(arr, 3);
for(int a:ans){
System.out.println(a);
}
}
public static int[] getMaxWindow(int[] arr,int w){
LinkedList<Integer> linkedList=new LinkedList<Integer>();
int[] ans=new int[arr.length-w+1];
for(int i=0;i<arr.length;i++){
while(!linkedList.isEmpty()&&arr[linkedList.peekLast()]<arr[i])
linkedList.removeLast();
linkedList.addLast(i);
if(linkedList.peekFirst()==(i-w))
linkedList.removeFirst();
if(i>=w-1)
ans[i-(w-1)]=arr[linkedList.getFirst()];
}
return ans;
}
}
复制代码