【问题标题】:Max element of an array in JavaJava中数组的最大元素
【发布时间】:2014-03-10 23:20:20
【问题描述】:

好的,我正在尝试查找数组中的最大元素,但我意识到这不是最好的方法,它只在某些情况下有效。希望能提供一些关于如何更改我的代码以使其适用于所有实例的指示。

public static int maxArray(int[] a) {
    int max = 0;
    for (int j = 0; j < a.length-1; j++) {
        if (a[j+1] > a[j]) {
            max = a[j+1];
        } else {
            max = a[j];
        }

    }
    return max;

}

【问题讨论】:

标签: java arrays max


【解决方案1】:

我建议你这样做,

max = a[0]; 开始,然后使用j1 循环到a.length。 比较a[j]max,即如果a[j] &gt; max 则设置max = a[j];

【讨论】:

  • 我唯一的其他建议是处理 null 和空数组。那是if (a == null || a.length == 0) return null;
【解决方案2】:

使用这个方法。

public static int maxArray(int[] a) {

int max = a[0]; // saves a bit of time

for (int j = 1; j < a.length; j++) {
    if (a[j] > max) {
        max = a[j];
    }

}
return max;

}

这是相当快速和简洁的。

【讨论】:

  • 我会从j = 1开始你的循环,循环到j &lt; a.length,然后检查是否a[j] &gt; max
  • 实际上,通过添加 if 检查,您使 saves a bit of time 比从索引 0 开始并使用 Integer.MIN_VALUE 作为初始最大值要贵一些
【解决方案3】:

您需要将当前元素与最大元素进行比较,而不是与下一个元素进行比较。

if (a[j] > max) {
    max = a[j];
}

【讨论】:

    【解决方案4】:

    在 Java 8 中你可以使用 Stream:

    public static int maxArray(int[] a) {
        return Arrays.stream(a).max().getAsInt();
    }
    

    【讨论】:

      【解决方案5】:
      public static <T extends Object & Comparable<? super T>> T maxArray(T[] array) {
          return Collections.max(Arrays.asList(array));
      }
      

      调用函数后,例如:

      整数[] a = { 1, 5, -6, 3, 0, 2 };

      整数最大值 = maxArray(a);

      System.out.println(max);

      【讨论】:

      • 请注意,这是int[],而不是T[]。这行不通。另请注意,T extends Object &amp; Comparable&lt;? super T&gt; 中的 Object 是多余的。
      • 为了冗余,max函数的声明为:public static &lt;T extends Object &amp; Comparable&lt;? super T&gt;&gt; T max(Collection&lt;? extends T&gt; coll)
      • 我假设您是从source of Collections 复制的。那里有backwards compatibility。在您的示例中没有理由使用它。
      • 是的,&lt;T extends Comparable&gt; 并添加演员以返回:(T)
      【解决方案6】:
      public static int getMaxElement(int[] elements) {
          int max = elements[0];
          for (int j = 0; j < elements.length-1; j++) {
              if (elements[j] > max) {
                  max = elements[j];
              }
          }
          return max;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-23
        • 1970-01-01
        • 2011-05-26
        • 2012-05-11
        • 2012-10-17
        • 2018-08-24
        • 2017-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多