===查找众数及中位数
题目描述
1.众数是指一组数据中出现次数量多的那个数,众数可以是多个
2.中位数是指把一组数据从小到大排列,最中间的那个数,如果这组数据的个数是奇数,那最中间那个就是中位数,如果这组数据的个数为偶数,那就把中间的两个数之和除以2,所得的结果就是中位数
3.查找整型数组中元素的众数并组成一个新的数组,求新数组的中位数
输入描述 输出描述 public class ModeMedius { // 众数的中位数
输入一个一维整型数组,数组大小取值范围 0
输出众数组成的新数组的中位数
import java.util.*;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] str = in.nextLine().split(" ");
int[] nums = new int[str.length];
for (int i = 0; i < str.length; i++) {
nums[i] = Integer.parseInt(str[i]);
}
// hashmap统计出现的次数
HashMap
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
// 按出现次数排序
List
list.sort((o1, o2) -> o2.getValue() - o1.getValue());
int max = 0;
// 获取众数列表
List
for (Map.Entry
if (entry.getValue() >= max) {
mode.add(entry.getKey());
max = entry.getValue();
} else {
break;
}
}
// 计算中位数
int medium = 0;
int length = mode.size();
if (length % 2 == 0) {
medium = (mode.get(length / 2 - 1) + mode.get(length / 2)) / 2;
} else {
medium = mode.get(length / 2);
}
System.out.println(medium);
}
}



