最常见的整数java?

时间:2013-08-10 06:14:32

标签: java algorithm collections

如何检测java中模式的反面?

例如,如果我想在数组中找到最不常见的数字,我该怎么做?

感谢。

我尝试了什么:

public int getLeastCommonNum(int[] array)
{
int min = array[0];
int pos = 0;
for (int i = 1; i < array.length; i++)
{
    if (array[i] < min) 
    {
    min = array[i]; 
    pos = i; 
    }
}
return array[pos];
}

2 个答案:

答案 0 :(得分:1)

我在这里提出了使用HashMap

的解决方案
public int getLeastCommonNum(int[] array)
{
    Map<Integer, Integer> occurrences = new HashMap<Integer, Integer> ();
    for (int num : array) {
       if (occurrences.containsKey(num)) {
           occurrences.put(num, occurrences.get(num) + 1);
       } else {
           occurrences.put(num, 1);
       }
    }
    int minOccurred = -1;
    int minOccurredCnt = -1;
    for (Map.Entry<Integer, Integer> occurrencesEntry : occurrences.entrySet()) {
        if (minOccurredCnt == -1 || minOccurredCnt > occurrencesEntry.getValue()) {
            minOccurredCnt = occurrencesEntry.getValue();
            minOccurred = occurrencesEntry.getKey();
        }
    }
    return minOccurred ;
}

我已经用心编码了所有内容,所以可能是我有一些小的拼写错误。

答案 1 :(得分:0)

基于Boris Strandjev版本,但使用Multiset进行计数:

@Nullable
public Integer getLeastCommonNumV2(final int[] array)
{
    // step 1: count
    final Multiset<Integer> occurances = HashMultiset.create();
    for (final int num : array) {
        occurances.add(num);
    }

    // step 2: find least common
    Multiset.Entry<Integer> leastCommon = null;
    for (final Multiset.Entry<Integer> occurance : occurances.entrySet()) {
        if (leastCommon == null || occurance.getCount() < leastCommon.getCount()) {
            leastCommon = occurance;
        }
    }
    return leastCommon == null ? null : leastCommon.getElement();
}