版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37767529/article/details/82590539
问题描述 给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。 输入格式 输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。 输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。 输出格式 输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。 样例输入 6 10 1 10 20 30 20 样例输出 10 |
解析:这次不同的是,需要将出现最多次数的数输出,而不是输出次数。这次定义的最大的特点就是,将数值作为数组的编号,将次数作为数组的值,然后计算出每个输入的数出现次数。最后对次数进行大小比较,最后输出结果。
import java.util.Scanner;
public class demo1312_1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[10001];
for(int i=0;i<n;i++) {
//arr[sc.nextInt()]++;
int temp=sc.nextInt();
arr[temp]=arr[temp]+1;
}
int max=-1;
int result=0;
for(int i=1;i<10001;i++) {
if(arr[i]>max) {
max=arr[i];
result=i;
}
}
System.out.println(result);
}
}