题解 | #成绩排序#

成绩排序

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

直接排序就ok了,使用Java集合的排序器,自定义排序规则

import java.util.*;

class Score{
    String name;
    int value;
    int seq;
}

public class Main{
    
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        final int order = sc.nextInt(); // 0是倒序,1是正序
        Comparator comparator = new Comparator<Score>(){
            public int compare(Score s1, Score s2){
                if(order == 0){
                    return s1.value != s2.value ? s2.value - s1.value : s1.seq - s2.seq;
                }else if(order == 1){
                    return s1.value != s2.value ? s1.value - s2.value : s1.seq - s2.seq;
                }
                return 0;
            }
        };
        List<Score> list = new ArrayList<>();
        sc.nextLine();
        for(int i = 0; i < n; i++){
            Score score = new Score();
            String line = sc.nextLine();
            String[] lines = line.split(" ");
            score.name = lines[0];
            score.value = Integer.valueOf(lines[1]);
            score.seq = i;
            list.add(score);
        }
        Collections.sort(list, comparator);
        for(Score score: list){
            System.out.println(score.name + " " + score.value);
        }
    }
    
}
全部评论

相关推荐

我即大橘:耐泡王
点赞 评论 收藏
分享
10-25 00:32
香梨想要offer:感觉考研以后好好学 后面能乱杀,目前这简历有点难
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务