有一個整型數組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;
}
}
複製代碼