java - double 组——最常见的值方法? (没有 HashMap 或排序)

标签 java arrays frequency

我已经弄清楚如何创建一个整数数组并创建一个方法来查找数组中最常见的值。通过创建另一个用作每个值的计数器的数组来创建此方法。但是我该如何创建一个方法来查找 double 组中最常见的 double ......而不使用 HashMap 或排序呢?

-这是我使用整数的方法的代码,但不适用于 double 值/ double 组

public static int findMostFrequentValue(int[] array) {
    int i;
    int[] numberCount = new int[100];

    for (i = 0; i < array.length; i++)
        ++numberCount[array[i]];

    int max = 0;
    int j;

    for (j = 0; j < numberCount.length; j++) {
        if (numberCount[j] > max) max = j;
    }

    return max;
}

最佳答案

这是一个简短的简介,坚持您不使用 HashMap 或排序的要求。请注意,按照编码,如果出现平局,则返回最后一个匹配项。另请注意,这是内部循环的指数 O(n^2) 时间,对于大型数组来说非常糟糕。

public class Frequency {

    public static void main(String args[]) {
        double[] array = {3.4, 6.8, 1.1, 2.4, 3.8, 6.8, 7.0, 5.0};
        double result = findMostFrequentValue(array);

        System.out.println("Most frequent value: " + result);
    }

    public static double findMostFrequentValue(double[] array) {
        int[] count = new int[array.length];

        for (int i = 0; i < array.length; i++) {
            count[i] = 0;
            for (int j = 0; j < array.length; j++) {
                if (approxEquals(array[i], array[j], .0001)) {
                    count[i]++;
                }
            }
        }

        int index = 0;
        int max = 0;
        for (int i = 0; i < count.length; i++) {
            if (count[i] > max) {
                max = count[i];
                index = i;
            }
        }

        return array[index];
    }

    private static boolean approxEquals(double val1, double val2, double tolerance) {
        return Math.abs(val1 - val2) < tolerance;
    }

}

关于java - double 组——最常见的值方法? (没有 HashMap 或排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417313/

相关文章:

Java Swing : Displaying images from within a Jar

python - 按最近的 "seed"区域对 Python 数组进行分类?

python - 如果数字按降序排列,则返回 true

java - 为什么设置数组 A 值的行会重置我在数组 B 中的值?

java - 简单的Java数组问题

Python降序字数

python - 以 float 组获取音频频率和幅度

java - 对同一 JPA 模型的多次调用会覆盖该对象

java - JFileChooser 不允许选择目录

java - java中私有(private)对象是如何传递的?