在这里,我提出了一个解决方案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 ;
}
我已经把所有东西都记下来了,所以可能是我有一些小的拼写错误。