2512. 奖励最顶尖的 K 名学生

题目#

题解#

Map + Map#

class Solution {
    public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {

        // 将分数放到 Map 中
        Map<String, Integer> score = new HashMap<>();
        for (String s : positive_feedback) {
            score.put(s, 3);
        }
        for (String s : negative_feedback) {
            score.put(s, -1);
        }

        Map<Integer, Integer> idMap = new HashMap<>();
        for (int i = 0; i < student_id.length; i++) {
            String rep = report[i];
            String[] split = rep.split(" ");
            int cur = 0;
            for (String s : split) {
                cur += score.getOrDefault(s, 0);
            }
            idMap.put(student_id[i], cur);
        }
        // 对 key 进行排序
        return idMap.entrySet().stream().sorted((o1, o2) -> {

                    if (Objects.equals(o1.getValue(), o2.getValue())) {
                        return o1.getKey() - o2.getKey();
                    }
                    return o2.getValue() - o1.getValue();
                }).map(Map.Entry::getKey)
                .limit(k)
                .collect(Collectors.toList());

    }
}

Map + 二维数组#

class Solution {
    public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {

        // 将分数放在 Map
        Map<String, Integer> score = new HashMap<>();
        for (String s : positive_feedback) {
            score.put(s, 3);
        }
        for (String s : negative_feedback) {
            score.put(s, -1);
        }

        int[] scores = new int[student_id.length];
        int[][] idArrs = new int[student_id.length][2];
        for (int i = 0; i < student_id.length; i++) {
            String rep = report[i];
            String[] split = rep.split(" ");
            int cur = 0;
            for (String s : split) {
                cur += score.getOrDefault(s, 0);
            }
            // 分数-学号
            idArrs[i] = new int[]{cur, student_id[i]};
        }
        // 二维数组进行排序
        Arrays.sort(idArrs, (o1, o2) -> {
            if (o1[0] == o2[0]) {
                return o1[1] - o2[1];
            }

            return o2[0] - o1[0];
        });

        ArrayList<Integer> res = new ArrayList<>(k);
        for (int i = 0; i < k; i++) {
            res.add(idArrs[i][1]);
        }
        return res;
    }
}

作者:程序员小航

出处:https://www.cnblogs.com/liuzhihang/p/17758525.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。


欢迎关注个人公众号:『 程序员小航 』

posted @   程序员小航  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu