繁体   English   中英

双精度数组-最频繁的取值方法? (没有哈希图或排序)

[英]Array of doubles — most frequent value method? (without hashmaps or sorting)

我已经弄清楚了如何创建一个整数数组并创建一种方法来查找数组中最频繁的值。 通过创建另一个用作每个值的计数器的数组来创建此方法。 但是我将如何创建一种用于在双倍数组中查找最频繁的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;
}

这是一个快速的说明,坚持不要求哈希图或排序的要求。 请注意,按照编码,如果有平局,则返回最后一场比赛。 还要注意,这是带有内循环的 指数 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;
    }

}

暂无
暂无

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

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