简体   繁体   English

从 MAX_VALUE 中查找数组的最小值

[英]Finding the minimum of an array from MAX_VALUE

Currently I am trying to find the minimum value within the array.目前我正试图在数组中找到最小值。 The user types in the array they want to create and then the program is supposed to find the minimum.用户输入他们想要创建的数组,然后程序应该找到最小值。 I have tried using the max_int value to find he minimum but I haven't had any success.我曾尝试使用 max_int 值来找到他的最小值,但我没有取得任何成功。 How can I find the minimum within the array?如何找到数组中的最小值?

public class Recursion {

    public static int findMin(int[] array, int index, int min) {
        int smallest = Integer.MAX_VALUE;
        for (int i = 0; i < array.length; i++) {
            if (array[i] < smallest) {
                smallest = array[i];
            }
            return findMin(array, index, min);
        }
        return smallest;
    }
}

From your description, you just need to find the min value in the array, so you don't need to use recursion for this problem.根据你的描述,你只需要找到数组中的最小值,所以你不需要使用递归来解决这个问题。 The following is an adaptation from your original code that does the job.以下是对完成这项工作的原始代码的改编。

public static int findMin(int[] array) {
    int smallest = Integer.MAX_VALUE;
    for (int i = 0; i < array.length; i++) {
        if (array[i] < smallest) {
            smallest = array[i];
        }
    }
    return smallest;
}

If you can use the Stream interface, you can use a one liner for this problem.如果你可以使用Stream接口,你可以使用 one liner 来解决这个问题。

 public static int findMin(int[] array) {
  return Arrays.stream(array).min().getAsInt();
}

Why do not just find min?为什么不直接找min?

public static int findMin(int[] arr) {
    int min = Integer.MAX_VALUE;
    
    for (int a : arr)
        min = Math.min(min, a);

    return min;
}

or even:甚至:

public static int findMin(int[] arr) {
    return Arrays.stream(arr).min().getAsInt();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM