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

题目

题解

Map + Map

java 复制代码
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 + 二维数组

java 复制代码
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;
    }
}

本文由mdnice多平台发布

相关推荐
薛定谔的悦3 小时前
MQTT通信协议业务层实现的完整开发流程
java·后端·mqtt·struts
enjoy嚣士4 小时前
springboot之Exel工具类
java·spring boot·后端·easyexcel·excel工具类
无限大64 小时前
职场逻辑03:3步搞定高效汇报,让领导看到你的价值
后端
盐水冰5 小时前
【烘焙坊项目】后端搭建(12) - 订单状态定时处理,来单提醒和顾客催单
java·后端·学习
紫丁香5 小时前
AutoGen详解一
后端·python·flask
小涛不学习6 小时前
Spring Boot 详解(从入门到原理)
java·spring boot·后端
Victor3567 小时前
MongoDB(51)什么是分片?
后端
Victor3567 小时前
MongoDB(50)副本集中的角色有哪些?
后端
IT_陈寒8 小时前
JavaScript开发者必看:5个让你的代码性能翻倍的隐藏技巧
前端·人工智能·后端
shengjk18 小时前
大数据工程师必看:为什么你的 IN 查询在 Flink/Spark 上慢到离谱?
后端