题解 | #成绩排序#

成绩排序

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

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int people = in.nextInt();
        int sort = in.nextInt();
        ArrayList<Score> al = new ArrayList();
        while (people > 0) {
            al.add(new Score(in.next(), in.nextInt()));
            people--;
        }
        al.sort(new ScoreComparator(sort));
        for (Score sc : al) {
            System.out.println(sc.name + " " + sc.score);
        }

    }
}
// creates the comparator for comparing score
class ScoreComparator implements Comparator<Score> {
    int sort;
    ScoreComparator(int sort) {
        this.sort = sort;
    }

    // override the compare() method
    public int compare(Score s1, Score s2) {
        // 其底层原理为如果compare的返回值为正数, 就交换两个比较元素的位置
        if (sort == 0) {
            // desc
            return s2.score - s1.score;
        } else {
            // acs
            return s1.score - s2.score;
        }
    }
}
class Score {
    String name;
    int score;
    Score(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

知识点: Comparator 的compare

全部评论

相关推荐

过往烟沉:我说什么来着,java就业面就是广!
点赞 评论 收藏
分享
10-17 10:05
已编辑
北华大学 全栈开发
牛客872465272号:掉头发了哥
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务