-1

java - 如何在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];
}
4

2 回答 2

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

我已经把所有东西都记下来了,所以可能是我有一些小的拼写错误。

于 2013-08-10T06:59:11.727 回答
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();
}
于 2013-08-10T07:41:13.417 回答