题解 | #成绩排序#

成绩排序

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());
        }
    }
}
全部评论

相关推荐

04-29 22:35
门头沟学院 Java
牛友说改了名字能收到offer:旧图新发查看图片
点赞 评论 收藏
分享
那么好了好了:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务