题解 | #成绩排序#

成绩排序

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

全部评论

相关推荐

10-25 17:00
门头沟学院 Java
点赞 评论 收藏
分享
offer飞来我手中:为啥现在看到大多数公司都有提前实习的要求
点赞 评论 收藏
分享
榕城小榕树:你别说,你还真别说,计算机实习薪资跟这个差不多
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务