考虑用map去处理,
然后筛选出map里值最大的元素集合,
最后集合中键最小的那个元素
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<Integer, Integer> maxMap = new HashMap<>();
int count = scanner.nextInt();
int[] nums = new int[count];
for (int i = 0; i < count; i++) {
nums[i] = scanner.nextInt();
}
// 从nums数组中找出现次数最多的元素
for (int item: nums){
if (maxMap.get(item) != null){
maxMap.put(item, maxMap.get(item)+1);
}else {
maxMap.put(item, 1);
}
}
int maxValue = Collections.max(maxMap.values());
List<Integer> maxValueKeys = maxMap.entrySet().stream()
.filter(entry ->entry.getValue() == maxValue)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
int min = 0;
for (Integer key : maxValueKeys){
if (min == 0){
min = key;
}else {
if (key <=min){
min = key;
}
}
}
System.out.println(min);
}
}
标签:map,scanner,nums,int,item,最小值,整型,数组,maxMap
From: https://www.cnblogs.com/za-ill-ds/p/17042835.html