问题描述
试题编号: | 201312-1 |
试题名称: | 出现次数最多的数 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: | 问题描述 给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。 输入格式 输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。 输出格式 输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。 样例输入 6 样例输出 10 |
package practice_20210831;
import java.util.*;
public class Main {
public static void main(String[] args) {
// 问题描述
// 给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
// 输入格式
// 输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
// 输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
// 输出格式
// 输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
// 样例输入
// 6
// 10 1 10 20 30 20
// 样例输出
// 10
run();
}
public static void run() {
//输入数字的个数n
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
//循环输入数字,将其存入数组
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
//构建Map,且要求能排序的Map,选取TreeMap,用以储存数字和数字的个数,number:cnt
Map<Integer,Integer> map=new TreeMap<Integer, Integer>();//默认按照key的升序排序
int cnt=0;
for (int num : nums) {
Integer value = map.getOrDefault(num, 0);
value++;
map.put(num,value);
}
//遍历map找出出现次数最多的数字,且需要满足 如果次数最多的一样,要取最小的数
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
int max_num=0;
int max_cnt=0;
for (Map.Entry<Integer, Integer> entry : entries) {
Integer key = entry.getKey();
Integer value = entry.getValue();
if(value>max_cnt)
{
max_cnt=value;
max_num=key;
}
}
System.out.println(max_num);
}
}
测评结果:100分。