Day13力扣打卡

打卡记录

奖励最顶尖的 k 名学生(哈希表+排序)

用哈希表对所有的positive与negative词条进行映射,然后遍历求解。tip:常用的分割字符串的操作:1.stringstream配合getline() [格式buf, string, char]2.string.find()[find未找到目标会返回npos]配合string.substr()

cpp 复制代码
class Solution {
public:
    vector<int> topStudents(vector<string>& positive_feedback, vector<string>& negative_feedback, vector<string>& report, vector<int>& student_id, int k) {
        unordered_set<string> pos, neg;
        for (auto& s : positive_feedback) pos.insert(s);
        for (auto& s : negative_feedback) neg.insert(s);
        vector<pair<int, int>> arr;
        int n = student_id.size();
        for (int i = 0; i < n; ++i) {
            stringstream ss;
            ss << report[i];
            string tmp;
            int res = 0;
            while (getline(ss, tmp, ' ')) {
                if (pos.count(tmp)) res += 3; 
                else if (neg.count(tmp)) res--;
            }
            arr.push_back({-res, student_id[i]});
        }
        sort(arr.begin(), arr.end());
        vector<int> ans(k);
        for (int i = 0; i < k; ++i) ans[i] = arr[i].second;
        return ans;
    }
};
相关推荐
power 雀儿5 分钟前
掩码(Mask)机制 结合 多头自注意力函数
算法
会叫的恐龙9 分钟前
C++ 核心知识点汇总(第六日)(字符串)
c++·算法·字符串
小糯米60120 分钟前
C++顺序表和vector
开发语言·c++·算法
独望漫天星辰30 分钟前
C++ 多态深度解析:从语法规则到底层实现(附实战验证代码)
开发语言·c++
We་ct41 分钟前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
Lionel6891 小时前
分步实现 Flutter 鸿蒙轮播图核心功能(搜索框 + 指示灯)
算法·图搜索算法
小妖6661 小时前
js 实现快速排序算法
数据结构·算法·排序算法
xsyaaaan1 小时前
代码随想录Day30动态规划:背包问题二维_背包问题一维_416分割等和子集
算法·动态规划
王老师青少年编程1 小时前
2024年信奥赛C++提高组csp-s初赛真题及答案解析(阅读程序第3题)
c++·题解·真题·csp·信奥赛·csp-s·提高组
凡人叶枫2 小时前
C++中输入、输出和文件操作详解(Linux实战版)| 从基础到项目落地,避坑指南
linux·服务器·c语言·开发语言·c++