题解 | #成绩排序#
成绩排序
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
查看13道真题和解析