题解 | #成绩排序#

成绩排序

https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) {
            int num = in.nextInt();
            int order = in.nextInt();
            Map<String, Integer> hashmap = new LinkedHashMap<>();
            Map<String, String> namemap = new HashMap<>();
            for (int i = 0 ; i < num ; ++i) {
                String name = in.next();
                int score = in.nextInt();
                if (hashmap.containsKey(name)) {
                    String temp = name;
                    while (hashmap.containsKey(temp)) {
                        temp += name;
                    }
                    namemap.put(temp, name);
                    hashmap.put(temp, score);
                } else {
                    hashmap.put(name, score);
                }
            }

            List<Map.Entry<String, Integer>> maplist = new ArrayList<>(hashmap.entrySet());
            if (order == 1) {
                Collections.sort(maplist, new Comparator<Map.Entry<String, Integer>>() {
                    @Override
                    public int compare(Map.Entry<String, Integer> m1,
                                       Map.Entry<String, Integer> m2) {
                        return m1.getValue() - m2.getValue();
                    }
                });

            } else {
                Collections.sort(maplist, new Comparator<Map.Entry<String, Integer>>() {
                    @Override
                    public int compare(Map.Entry<String, Integer> m1,
                                       Map.Entry<String, Integer> m2) {
                        return m2.getValue() - m1.getValue();
                    }
                });
            }
            for (int i = 0 ; i < maplist.size() ; ++i) {
                String key = maplist.get(i).getKey();
                if(namemap.containsKey(key)){
                    key = namemap.get(key);
                }
                System.out.println(key + " " + maplist.get(i).getValue());
            }
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务