Finding the max/min value in an array of primitives using Java

前端 未结 15 1854
遥遥无期
遥遥无期 2020-11-22 05:09

It\'s trivial to write a function to determine the min/max value in an array, such as:

/**
 * 
 * @param chars
 * @return the max value in the array of chars         


        
15条回答
  •  有刺的猬
    2020-11-22 05:15

    Here is a solution to get the max value in about 99% of runs (change the 0.01 to get a better result):

    public static double getMax(double[] vals){
        final double[] max = {Double.NEGATIVE_INFINITY};
    
        IntStream.of(new Random().ints((int) Math.ceil(Math.log(0.01) / Math.log(1.0 - (1.0/vals.length))),0,vals.length).toArray())
                .forEach(r -> max[0] = (max[0] < vals[r])? vals[r]: max[0]);
    
        return max[0];
    }
    

    (Not completely serious)

提交回复
热议问题