Java 跟踪双精度数组中最常出现的元素

Java 跟踪双精度数组中最常出现的元素,java,arrays,data-structures,Java,Arrays,Data Structures,假设我有一系列的双打,比如 [1.2,1.2,3.0,2.7,1.2] 我如何实现一个返回最频繁出现的元素频率的方法?在本例中,我只想创建一个方法,对双精度1.2返回3 这里有一个简单的方法可以做到这一点: public static int mostOccurances(double[] input) { Map<Double, Integer> map = new HashMap<>(); // Go over the input and store

假设我有一系列的双打,比如

[1.2,1.2,3.0,2.7,1.2]


我如何实现一个返回最频繁出现的元素频率的方法?在本例中,我只想创建一个方法,对双精度1.2返回3

这里有一个简单的方法可以做到这一点:

public static int mostOccurances(double[] input) {
    Map<Double, Integer> map = new HashMap<>();

    // Go over the input and store in map
    for (double d : input) {
        Integer count = map.get(d);
        if (count == null) {
            map.put (d, 1);
        } else {
            map.put (d, count + 1);
        }
    }

    // Go over the map and return the maximum occurrence
    // assumption: if input is empty, it's OK to return 0
    int retVal = 0;
    for (int count : map.values()) {
        retVal = Math.max(retVal, count);
    }

    return retVal;
}

对于HashMap,键是double的值,值是发生数。你应该能够自己通过数组计算出实际的循环。第一步是努力向我们展示它是什么,什么不起作用。我想我知道如何使用哈希映射为每个元素编写频率计数器,但是我如何检查哪个元素是最频繁出现的呢?值最高的hashMap元素是最频繁出现的。看看这篇文章,应该可以帮助您: