左神带你刷题之生成窗口最大值数值

题目描述:

  有一个整型数组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)

原文地址:https://www.cnblogs.com/rrttp/p/8719620.html