繁体   English   中英

Java:这种在整数数组中找到最大值的方法是否正确?

[英]Java: is this way of finding the maximum value in an integer array correct?

我试图在整数数组中找到最大值。 我不想在任何地方使用双打。

public static int findMax(int...vals) {
    int max = Integer.MIN_VALUE;
    for (int d: vals) {
        if (d > max) max = d;
    }
    return max;
}

使用整数包装器而不是基元怎么样...

最好的部分是您可以使用集合并有效地获得最大值

public static int findMax(Integer[] vals) {

   return Collections.max(Arrays.asList(vals));
}

 public static int findMax(int[] vals) {
    List<Integer> l = new ArrayList<>();    
    for (int d: vals) {
        l.add(d);
    }

    return Collections.max(l);
 }

我建议用第一个值初始化 max,如果没有传递值则抛出异常。

public static int findMax(int...vals) {
    int max;
    // initialize max
    if (vals.length > 0) {
        max = vals[0];
    }
    else throw new RuntimeException("findMax requires at least one value");
    for (int d: vals) {
        if (d > max) max = d;
    }
    return max;
}

或者只是

public static int findMax(int...vals) {
    int max = vals[0];
    for (int d: vals) {
        if (d > max) max = d;
    }
    return max;
}

另一个想法是使用递归:

private int getMaxInt(int... ints) {
        if (ints.length == 1) return ints[0];
        else return Math.max(ints[0], getMaxInt(Arrays.copyOfRange(ints, 1, ints.length)));
    }

暂无
暂无

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

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