如何在Java中的子数组中找到最小值

时间:2019-06-15 11:56:54

标签: java arrays

我的考试未能显示。

请帮助实现此目标

给出大小为N和整数k的数组A []。工作是为每个大小为k的子数组打印最小元素。

For Each valid index i(0<=i <=N -K) Have to print min(A[i],A[i+1],A[i+2]...A[i+k]).

输入格式: 第一行将包含两个整数N和k。 第二行包含N个整数,它们表示数组A []

的元素

约束:

1 <=N <=10^5
1<=K <= N
1<=A[i] <=10^6

输出格式 打印每个用空格分隔的大小为k的子数组的最小元素。

输入:

5 2
10 0 3 2 5

输出:

0 0 2 2

但是我尝试的是找到最大元素:

我知道这是错误的。但是我只知道这一点。

public static int maxSum(int arr[], int n, int k) 
    { 
        // k must be greater 
        if (n < k) 
        { 
           System.out.println("Invalid"); 
           return -1; 
        } 

        // Compute sum of first window of size k 
        int res = 0; 
        for (int i=0; i<k; i++) 
           res += arr[i]; 

        // Compute sums of remaining windows by 
        // removing first element of previous 
        // window and adding last element of  
        // current window. 
        int curr_sum = res; 
        for (int i=k; i<n; i++) 
        { 
           curr_sum += arr[i] - arr[i-k]; 
           res = Math.max(res, curr_sum); 
        } 

        return res; 
    } 

    /* Driver program to test above function */
    public static void main(String[] args)  
    { 
        int arr[] = {5,2,10,0,3,2,5}; 
        int k = 7; 
        int n = arr.length; 
        System.out.println(maxSum(arr, n, k)); 
    } 
} 

1 个答案:

答案 0 :(得分:0)

这是我在大约5分钟内编写的非常简单的解决方案。 注意,我不执行输入,nkarray值只是用main方法硬编码的。

package stackoverflow;

public class MinimumSubArray {

    public static void main(String[] args) {
        solve(5, 2, new int[]{ 10, 0, 3, 2, 5 }); // expect 0 0 2 2
        solve(5, 2, new int[]{ 10, 0, 3, 2, 1 }); // expect 0 0 2 1
        solve(1, 1, new int[]{ 6 }); // expect 6
        solve(3, 3, new int[]{ 3, 2, 1 }); // expect 1
        solve(3, 1, new int[]{ 3, 2, 1 }); // expect 3 2 1
    }

    private static void solve(final int n, final int k, final int[] array) {
        if (n != array.length)
            throw new IllegalArgumentException( String.format("Array length must be %d.", n) );

        if (k > n)
            throw new IllegalArgumentException( String.format("K = %d is bigger than n = %d.", k, n) );

        int currentStartIndex = 0;

        while (currentStartIndex <= (n - k)) {
            int min = array[currentStartIndex];

            for (int i = currentStartIndex + 1; i < currentStartIndex + k; i++) {
                if (array[i] < min) {
                    min = array[i];
                }
            }

            System.out.printf("%d ", min); // print minimum of the current sub-array

            currentStartIndex++;
        }

        System.out.println();
    }
}
相关问题