题目大意:
输入N和M,N就是N次测试,M是说每次测试产生的数据个数,数据范围在1-10000之间。现要求统计输出N次测试中数据出现次数第二多的所有数。当输入0,0时结束。
样例:
4 5
20 33 25 32 99
32 86 99 25 10
20 99 10 33 86
19 33 74 99 32
3 6
2 34 67 36 79 93
100 38 21 76 91 85
32 23 85 31 88 1
0 0
Sample Output
32 33
1 2 21 23 31 32 34 36 38 67 76 79 88 91 93 100
分析:先统计,然后排序(用Arrays.sort()就可以了),注意输出的时候要按 play 的 num 的升序输出。
AC代码:
- import java.util.Scanner;
- import java.util.Arrays;
- class play implements Comparable {
- int num; //N次测试中出现的数字
- int s; //此数字在N次测试中出现的次数
- public int compareTo(Object o) {
- play b=(play)o;
- if(this.s==b.s) //s相等,按num升序
- return this.num-b.num;
- else
- return b.s-this.s; //按s从大到小降序排
- }
- public String toString(){
- return "["+num+","+s+"]";
- }
- }
- public class Main{
- public static void main(String args[]){
- int n,m;
- Scanner in=new Scanner(System.in);
- while(true){
- n=in.nextInt();
- m=in.nextInt();
- play p[]=new play[10001]; //数据范围在1-10000,数据i用play[i]来记录相关信息
- for(int i=0;i<10001;i++)
- p[i]=new play();
- int temp;
- if(n==0 && m==0)
- break;
- for(int i=0;i<n;i++)
- for(int j=0;j<m;j++)
- {
- temp=in.nextInt();//测试中出现的数字
- p[temp].num=temp;//记录这个数字
- p[temp].s++; //记录此数字出现的次数
- }
- Arrays.sort(p); //将p按s降序排序
- int i=1;
- while(p[i].s==p[i+1].s) //从下标1开始输出所有出现次数第二多的数字
- {
- System.out.printf("%d ",p[i].num);
- i++;
- }
- System.out.printf("%d\n",p[i].num);
- }
- }
- }
转载于:https://blog.51cto.com/ajiao13/1135737