【问题标题】:use of minimum values with array's in simple problems在简单问题中使用数组的最小值
【发布时间】:2017-04-29 08:23:39
【问题描述】:

我正在学习 Java,作为我工作的一部分,我需要能够计算数组中值的范围(最大值 - 最小值 + 1)。我不允许使用像 collections.min(array) 这样的方法。到目前为止我的解决方案是这样的:

public static int range(int[] data){
int min = 99999999;
int max = 0; 
int test = 0;
int range = 0;
for (int i = 0; i < data.length; i++){
     test = data[i];

     if (test > max)
         max = test;
     if (test < min) 
         min = test;
}
range = (max - min) + 1;
return range; 

}

虽然它适用于他们,但它并不是特别优雅。最小值为 9999999 是可行的,但如果我最终在使用大于该值的数字时遇到问题,它就不起作用。

我觉得应该有更好的解决方案,但我没有找到一种方法来找到最小值而不将我的 int min 设置为非常高的值。否则数组可能有非常大的数字,并且最小值永远不会改变,因为数组中的值总是大于它。

【问题讨论】:

  • 考虑使用 Integer.MIN_VALUE && MAX_VALUE
  • 也不需要存储range只需返回(max - min) + 1
  • Java 中有一个预定义的值叫做 Integer.MAX_VALUE,它等于 2^31 - 1,这是一个 int 数的最大值。
  • Integerjava.lang 包中,这意味着它始终可以访问(因此Integer.MAX_VALUE 始终可以访问)。
  • @shmosel 感谢您指出这一点。顺便说一句,您在评论开头忘记了//

标签: java arrays range max minimum


【解决方案1】:

此方法返回至少一个元素的所有非空数组的范围,否则它会抛出一个IllegalArgumentException。这是通过max &gt;= min 的健全性检查来完成的,如果我们对minmax 的初始初始化值没有改变,则只有true。只有在跳过 for 循环时才会发生这种情况,这只发生在空数组或空数组中。如果数组包含任何有效的int,甚至是Integer.MAX_VALUEInteger.MIN_VALUE,则此完整性检查成功。

public static int range(int[] list){

    int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;

    for(int i = 0; list != null && i < list.length; i++){
        int current = list[i];

        if(current > max){
             max = current;
        }

        if(current < min){
             min = current;
        }
    }

    if(max >= min){
        return max-min+1;
    }
    else throw IllegalArgumentException("Zero-length and null arrays have an undefined range!");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 2016-10-06
    • 2017-10-01
    • 2013-12-06
    • 2015-06-23
    • 2020-10-24
    • 2010-12-07
    相关资源
    最近更新 更多