确定最屡见不鲜以阵列屡见不鲜、阵列

2023-09-11 02:24:06 作者:心被挖空

假设我有一个double数组,如下所示:

Assume I have an array of doubles that looks like the following:

Array[10] = {10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10}

我需要可以确定该MAJORTY表决数组中什么,在这种情况下,10,因为它是最经常出现的数目的函数... 当然还有就是当不存在多数的情况(他们是平等的),在这种情况下,我需要抛出一个异常...

I need a function that can determine what the MAJORTY vote is in the array, in this case "10" because it is the number that appears the most often... And of course there is the situation when no majority exists (where they are equal), in that case I need to throw an exception...

任何线索?除了做一些真讨厌循环阵列上(对于每个索引,确定有多少个具有相同值的存在,存储在阵列中的计数,然后扫描的计数阵列的最高数量,并在该位置上的值是赢家,等...)

Any clues? Aside from doing some really nasty looping on the array (for each index, determine how many exist with the same value, store a count in the array, and then scan the count array for the highest number and the value at that position is the winner, etc...)

谢谢

推荐答案

使用地图<整数,整数GT; 应该是简单的:

int mostFrequent(int... ary) {
    Map<Integer, Integer> m = new HashMap<Integer, Integer>();

    for (int a : ary) {
        Integer freq = m.get(a);
        m.put(a, (freq == null) ? 1 : freq + 1);
    }

    int max = -1;
    int mostFrequent = -1;

    for (Map.Entry<Integer, Integer> e : m.entrySet()) {
        if (e.getValue() > max) {
            mostFrequent = e.getKey();
            max = e.getValue();
        }
    }

    return mostFrequent;
}