2 回答

TA貢獻2011條經驗 獲得超2個贊
您的代碼不適用于此輸入:
HashMap<Integer, Integer> count = new HashMap<>();
count.put(1, 2);
count.put(2, 2);
count.put(4, 1);
因為您在mode = -1找到重復項后立即進行設置,而不是在最后進行設置。
您可以嘗試以下代碼,該代碼在 EntrySet 上進行 2 次傳遞。一次找到最大值,然后檢索具有該最大值的條目。
Integer max = count.values().stream()
.max(Integer::compareTo)
.orElse(-1);
List<Integer> maxEntries = count.entrySet().stream()
.filter(e -> e.getValue().equals(max))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Integer mode = maxEntries.size() == 1 ? maxEntries.get(0) : -1; //if there is a tie, mode is -1
System.out.println(mode);
為了能夠存儲大于 的值Integer,您可以使用Long和BigInteger。

TA貢獻1797條經驗 獲得超4個贊
正如 Kartik 已經說過的,您是對的,您的代碼中存在錯誤。最后還有一個循環:一旦找到與該值對應的鍵,您需要立即跳出它,或者mode可能在以后的迭代中再次更改導致不正確的結果。例如
new HashMap<>(Map.of(1, 3, 2, 1))
在這種情況下,您的代碼將正確確定最高計數為 3。查找相應鍵的循環將首先將 3 更改為 1,然后將 1 更改為 2。因此結果為 2,這是不正確的。基本問題是您使用相同的變量 ,mode有兩個目的,首先是模式的計數,其次是模式的 kay。不要那樣做?;煜娘L險太高了。
我想給出一個解決方案:
public static OptionalInt getModeIfUnique(Map<Integer, Integer> count) {
Optional<Integer> maxCount = count.values().stream().max(Comparator.naturalOrder());
OptionalInt modeKey = maxCount.flatMap(mc -> {
// Map containing only the entries having max count
Map<Integer, Integer> allModes = new HashMap<>(count);
allModes.values().removeIf(c -> c < mc);
if (allModes.size() == 1) {
return Optional.of(allModes.keySet().iterator().next());
} else {
return Optional.empty();
}
})
.map(OptionalInt::of)
.orElse(OptionalInt.empty());
return modeKey;
}
嘗試一下:
// Kartik’s example - should give no mode
System.out.println(getModeIfUnique(Map.of(1, 2, 2, 2, 4, 1)));
// My example - should give 1
System.out.println(getModeIfUnique(Map.of(1, 3, 2, 1)));
// Empty map - should give no mode
System.out.println(getModeIfUnique(Map.of()));
輸出:
OptionalInt.empty
OptionalInt[1]
OptionalInt.empty
添加回答
舉報