题解 | #成绩排序#用一个类包装一下,再使用比较器解决

成绩排序

https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b

import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Arrays;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int num = Integer.valueOf(in.nextLine());
        int way = Integer.valueOf(in.nextLine());
        ArrayList<student> ss = new ArrayList<>();
        student[] sss = new student[num];
        for(int i=0;i<num;i++){
            String str1 = in.nextLine();
            String[] str2 = str1.split(" ");
            String name = str2[0];
            Integer n = Integer.valueOf(str2[1]);
            student a = new student(n,name,i);
            sss[i]=a;
        } 
        if(way==0){
            Arrays.sort(sss,new Mycomp2());
            for(int i=0;i<sss.length;i++){
                System.out.println(sss[i].name+" "+sss[i].score);
            }
        }else{
            Arrays.sort(sss,new Mycomp());
            for(int i=0;i<sss.length;i++){
                System.out.println(sss[i].name+" "+ sss[i].score);
            }
        }
    }
    public static class student{
        public int score;
        public String name;
        public int number;
        public student(int s,String n,int num){
            score = s;
            name = n;
            number = num;
        }
    }
    public static class Mycomp implements Comparator<student>{
        @Override
        public int compare(student s1,student s2){
            return s1.score-s2.score == 0?s1.number-s2.number:s1.score-s2.score;
        }
    }

    public static class Mycomp2 implements Comparator<student>{
        @Override
        public int compare(student s1,student s2){
            return s2.score-s1.score == 0?s1.number-s2.number:s2.score-s1.score;
        }
    }
}

全部评论

相关推荐

缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务