确定数组中最常见的事件 [英] Determine the most common occurrence in an array

查看:121
本文介绍了确定数组中最常见的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一系列双打,如下所示:

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...)

推荐答案

使用 Map< Integer,Integer> 应该简单如下:

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;
}

这篇关于确定数组中最常见的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆