更新时间:2022-11-14 08:34:36
一些事情:
arrayMin
方法;min
应该是一个局部的 arrayMin
变量,而不是静态的;min
应初始化为 Integer.MAX_VALUE
.如果你用 1
初始化它,而 2
恰好是数组的最小值,你永远不会返回它;return min
,方法就结束了.可能对 变量 min 将返回第 i 个元素中的最小数字 短语有些混淆.这可能意味着在每次迭代中,变量min
将有(不返回)第一个i的最小数字代码>元素.
arrayMin
method;min
should be a local arrayMin
variable, not static;min
should be initialized to Integer.MAX_VALUE
. If you initialize it with 1
, and 2
happens to be the min value of the array, you'll never return it;return min
, the method ends. There's probably some confusion over the the variable min will return the smallest number from the first i elements phrase. It probably means that in each iteration, the variable min
will have (not return) the smallest number from the first i
elements.这是一个重构:
public static int arrayMin(int[] arr) {
int i = 0;
int min = Integer.MAX_VALUE;
if (arr == null) {
return 0; // What if 0 is the minimum value? What do you want to do in this case?
} else {
while (i < arr.length) {
if (arr[i] < min) {
min = arr[i];
}
i++;
}
}
return min;
}