Java:是在整数数组中找到最大值的方式



我试图在整数数组中找到最高值。我宁愿在任何地方使用双打。

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

我建议用第一个值初始化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;
}

使用Integer包装器而不是原始图...

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

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);
 }

另一个想法是使用递归:

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)));
    }

最新更新