左神帶你刷題之生成窗口最大值數值
阿新 • • 發佈:2018-04-05
pack 生成 inf get -i int arr AI OS
題目描述:
有一個整型數組arr和一個大小為w的窗口從數組的最左邊滑到最右邊,窗口每次向右滑動一個位置。
比如 : 給定數組【4 3 5 4 3 3 6 7】
【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個窗口的最大值;
package april; import java.util.Scanner; public class Class_7 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("輸入數組元素的大小n:"); int n = in.nextInt() ; System.out.println("滑窗的窗口大小w:") ; int w = in.nextInt(); int [] arr = new int[n] ; for (int index=0 ; index<n;index++) { arr[index] = in.nextInt(); } int [] result = new int[n-w+1] ; Class_7 class7 = new Class_7() ; result = class7.huachuang(arr,w,result); in.close();for(int ele :result) { System.out.print(ele+" "); } } public int [] huachuang(int [] arr , int w,int [] result) { int [] arrw = new int[w] ; for (int i=0; i<=arr.length-w; i++) { for (int j=i ;j<w+i ;j++ ) { arrw[j-i] = arr[j] ; } result[i] = getMax(arrw) ; } return result ; } public int getMax(int [] arrw) { int max = Integer.MIN_VALUE ; for(int index = 0 ; index<arrw.length ; index++) { if (arrw[index]>max) { max = arrw[index]; } } return max ; } }
時間復雜度分析:O(n)
左神帶你刷題之生成窗口最大值數值