🌈 Scala 实现
题目描述:
- 众数是指一组数据中出现次数多的数,众数可以是多个。
- 中位数是指把一组数据从小到大排列,最中间的那个数;如果这组数据的个数是奇数,那最中间那个就是中位数;如果这组数据的个数为偶数,那就把中间的两个数之和除以2就是中位数。
- 查找整型数组中元素的众数并组成一个新的数组,求新数组的中位数。
输入描述:
- 输入一个一维整型数组,数组大小取值范围 0<n<1000
- 数组中每个元素取值范围, 0<e<1000
输出描述:
- 输出众数组成的新数组的中位数。
示例
输入:
10 11 21 19 21 17 21 16 21 18 16
输出:
21
输入:
2 1 5 4 3 3 9 2 7 4 6 2 15 4 2 4
输出:
3
输入:
5 1 5 3 5 2 5 5 7 6 7 3 7 11 7 55 7 9 98 9 17 9 15 9 9 1 39
输出:7
代码:
def main(args: Array[String]): Unit = {
// 获取输入
val input = StdIn.readLine().split(" ").toList
// 记录数字出现的个数统计并排序
val map = new mutable.HashMap[String, Int]
for (elem <- input) {
map.put(elem, map.getOrElse(elem, 0) + 1)
}
val sortedList = map.toList.sortWith((o1, o2) => {
if (!o1._2.equals(o2._2)) {
o1._2.compareTo(o2._2) > 0
} else {
o1._1.compareTo(o2._1) > 0
}
})
// 将众数的元素添加到新的集合
val newList = sortedList.filter(_._2 == sortedList.head._2).map(_._1.toInt)
println(newList)
// 记录结果,并获取中位数
var res = 0
val length = newList.length
if (length % 2 == 0) {
res = (newList(length / 2) + newList(length / 2 - 1)) / 2;
} else {
res = newList(length / 2);
}
// 输出结果
println(res)
}
❤️ END ❤️