3 回答

TA贡献1995条经验 获得超2个赞
您可以检查maxKey并执行以下操作:
if(counts[a[i]] == maxCount && counts[a[i]] < maxKey) {
maxKey = counts[a[i]];
}
因此,如果有平局,maxKey则将设置为较小的元素。然后 ifcount[a[i]]永远大于maxCount,maxKey将被覆盖并成为最常出现的元素:
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贡献1786条经验 获得超11个赞
一个有趣的解决方案(我写得很开心)是首先Map通过流式传输数组并使用Collectors.groupingBywith来创建频率Collectors.counting()。
然后,我们可以流式传输并Collectors.groupingBy再次使用来创建一个Map<Long, SortedSet<Integer>>(键是频率,值是数组中具有该频率的排序值集)。
最后,我们可以对 进行排序,Map以便最高频率出现在最前面,然后简单地从 中获取最低的元素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贡献1840条经验 获得超5个赞
你想寻求最小值,所以我建议 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;
添加回答
举报