题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
int stuCount = in.nextInt();
int orderDirect = in.nextInt();
Set<Student> students;
if (orderDirect == 0) {
students = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.score >= o1.score ? 1 : -1;
}
});
}else{
students = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.score >= o2.score ? 1 : -1;
}
});
}
for (int i = 0; i < stuCount; i++) {
students.add(new Student(in.next(), in.nextInt()));
}
for(Student s:students){
s.println();
}
}
}
public static class Student {
public int score;
public String name;
public Student(String name, int score) {
this.score = score;
this.name = name;
}
public void println() {
System.out.println(name + " " + score);
}
}
}
查看15道真题和解析