英文:
Finding the minimum of an array from MAX_VALUE
问题
目前我正在尝试在数组中找到最小值。用户输入他们想要创建的数组,然后程序应该找到最小值。我尝试过使用最大整数值来找到最小值,但没有成功。如何在数组中找到最小值?
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;
}
}
英文:
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. 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;
}
}
答案1
得分: 4
根据您的描述,您只需在数组中找到最小值,因此您无需对此问题使用递归。以下是从您的原始代码进行适应的代码,可以完成任务。
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;
}
如果您可以使用 Stream
接口,您可以使用一行代码解决此问题。
public static int findMin(int[] array) {
return Arrays.stream(array).min().getAsInt();
}
英文:
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.
public static int findMin(int[] array) {
return Arrays.stream(array).min().getAsInt();
}
答案2
得分: 3
为什么不只是找到最小值?
public static int findMin(int[] arr) {
int min = Integer.MAX_VALUE;
for (int a : arr)
min = Math.min(min, a);
return min;
}
甚至可以这样:
public static int findMin(int[] arr) {
return Arrays.stream(arr).min().getAsInt();
}
英文:
Why do not just find 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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论