3 回答

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以檢查maxKey并執(zhí)行以下操作:
if(counts[a[i]] == maxCount && counts[a[i]] < maxKey) {
maxKey = counts[a[i]];
}
因此,如果有平局,maxKey則將設(shè)置為較小的元素。然后 ifcount[a[i]]永遠(yuǎn)大于maxCount,maxKey將被覆蓋并成為最常出現(xiàn)的元素:
for(int i = 0; i < a.length; i++) {
counts[a[i]]++;
if(counts[a[i]] > maxCount) {
maxCount = counts[a[i]];
maxKey = a[i];
}
if(counts[a[i]] == maxCount && counts[a[i]] < maxKey) {
maxKey = a[i];
}
}
System.out.println(a[maxKey]);
輸出
20

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
一個(gè)有趣的解決方案(我寫得很開心)是首先Map通過流式傳輸數(shù)組并使用Collectors.groupingBywith來創(chuàng)建頻率Collectors.counting()。
然后,我們可以流式傳輸并Collectors.groupingBy再次使用來創(chuàng)建一個(gè)Map<Long, SortedSet<Integer>>(鍵是頻率,值是數(shù)組中具有該頻率的排序值集)。
最后,我們可以對 進(jìn)行排序,Map以便最高頻率出現(xiàn)在最前面,然后簡單地從 中獲取最低的元素SortedSet:
int[] a = {34, 34, 20, 20, 15};
var lowest = Arrays.stream(a)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toCollection(TreeSet::new))))
.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getKey, Comparator.reverseOrder()))
.map(Map.Entry::getValue)
.mapToInt(TreeSet::first)
.findFirst();
lowest.ifPresent(System.out::println);
輸出:
20

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
你想尋求最小值,所以我建議 put int maxKey = Integer.MAX_VALUE;
然后每次找到更好的counts,就必須比較更新maxKey,畢竟解決方案是這樣的
int[] counts = new int[101];
int maxCount = 0;
int maxKey = Integer.MAX_VALUE;
for(int i = 0; i < a.length; i++) {
counts[a[i]]++;
if(counts[a[i]] >= maxCount) {
maxCount = counts[a[i]];
if(a[i] < maxKey) maxKey = a[i];
}
}
System.out.println(maxKey);
return maxKey;
添加回答
舉報(bào)