题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
本题的重点在于:
1.使用LinkedHashMap,在存放信息时,记录存放的顺序;
2.将map放入list中,以方便排序;
3.重写Comparator,定义新的排序规则,使用list.sort进行排序
需要注意的是:
在输入的得分信息中,可能出现重复的姓名,此时可以判断加入序号i,避免得分被覆盖,在最后输出是删去加入的记号i。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int order = Integer.parseInt(scan.nextLine());
Map<String, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < n; i++) {
String key = scan.next();
int value = scan.nextInt();
if (map.keySet().contains(key)) {
map.put(key + i, value);
} else {
map.put(key, value);
}
}
//排序
List<Map.Entry> list = new ArrayList<>(map.entrySet());
// list.sort(new Comparator<Map.Entry>(){
// public int compare(Map.Entry e1,Map.Entry e2){
// if(order==1){
// return (int)e1.getValue()-(int)e2.getValue();
// }else {
// return (int)e2.getValue()-(int)e1.getValue();
// }
// }
// });
list.sort((e1, e2) -> {
if (order == 1) {
return (int)e1.getValue() - (int)e2.getValue();
} else {
return (int)e2.getValue() - (int)e1.getValue();
}
});
//输出
for (Map.Entry e : list) {
String key = (String) e.getKey();
System.out.println(key.replaceAll("[0-9]", "") + " " + e.getValue());
}
}
}



查看6道真题和解析