【華為機試068】成績排序
阿新 • • 發佈:2018-12-24
題目描述:
輸入任意(使用者,成績)序列,可以獲得成績從高到低或從低到高的排列,相同成績
都按先錄入排列在前的規則處理。
例示:
jack 70
peter 96
Tom 70
smith 67
從高到低 成績
peter 96
jack 70
Tom 70
smith 67
從低到高
smith 67
Tom 70
jack 70
peter 96
Java實現:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int total = sc.nextInt();
int type = sc.nextInt();
Student[] scores = new Student[total];
for (int i = 0; i < total; i++) {
String name = sc.next();
int score = Integer.parseInt(sc.next());
scores[i] = new Student(name, score);
}
if (type == 0) {
//從大到小
Arrays.sort(scores, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.score - o1.score;
}
});
} else {
Arrays.sort(scores, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.score - o2.score;
}
});
}
for (Student s : scores) {
System.out.println(s.name + " " + s.score);
}
}
}
}
class Student {
String name = "";
int score = 0;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
}
知識點:
- Arrays.sort可以傳入自定義物件的陣列和比較器