• 计数排序-自然顺序Comparable


    题目大意:     输入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
    ",p[i].num);  
        }  
      }
    }  
    
    
    
  • 相关阅读:
    nginx 指令之 try_files
    java tomcat jvm优化
    使用phpexcel上传下载excel文件
    路由器数据统计SQL脚本
    微信公众平台开发(122) 获取微信会员卡用户姓名和手机号
    微信会员卡积分规则
    IP白名单
    关于公众平台接口不再支持HTTP方式调用的公告
    微信公众号特异功能列表
    微信小程序 TOP100 榜单
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/3170536.html
Copyright © 2020-2023  润新知