Leetcode刷题记录 2023/10/11

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

给定一组夸奖词与贬斥词列表,每个学生对应一个学生序号与评语,评语中每个夸奖词+3分,贬斥词-1分。给定一个数字K,找出评语得分最高的前K个学生并由分数高到低排序输出学生序号。

题目链接
中档题,但卡了一会儿。
题目的三个考点是:

  • 如何从句子中分割出单词
  • 如何高效的在单词列表中找匹配
  • 如何找出前K个学生

第一个点我们前面第一天就碰到过了,这里选用stringstream。传送门
第二个点选择使用哈希表,将两类单词表放入哈希表,之后分割出来的单词直接在哈希表里找对应即可。C++里,哈希表的实现有几种,常用的是unordered_map和unordered_set,加入后都可以直接使用count找对应单词的存在。

//map:S1/S2本身没区别,可以合并,在权值上作区分即可
unordered_map<string, int> words;
for (const auto& word : positive_feedback) {
	words[word] = 3;
}
for (const auto& word : negative_feedback) {
	words[word] = -1;
}
if(words.count(word)) point += words[word];
//set:没有第二个维
unordered_set<string> S1, S2;
for (const auto& word : positive_feedback) {
	S1.insert(word);
}
for (const auto& word : positive_feedback) {
    S2.insert(word);
}
if (S1.count(word)) point += 3;
else if (S2.count(word)) point --;

第三个点两种做法,第一种是全部排序只输出前K个,时间复杂度O(nlogn)(略),第二种则是使用大小为k的优先队列(堆),时间复杂度O(Nlogk),只管加入和超限弹出即可。
使用堆的情况下,由于要求是权值大序号小有限,可以选择自定义排序函数,也可以偷个懒,将权值取负。

int n = student_id.size();
for(int i = 0; i < student_id.size(); i++){
	int point = 0;
	stringstream feedback(report[i]);
	string word;
	while(feedback >> word){
		if(words.count(word)) point += words[word];
	}
	result.push(make_pair(-point, student_id[i]));
	if(result.size() > k) result.pop();
}
vector<int> sort_id;
while(!result.empty()){
   	sort_id.push_back(result.top().second);
	result.pop();
}
reverse(sort_id.begin(), sort_id.end());//小权值先出堆,整个结果队列需翻转
return sort_id;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值