原题链接:
https://leetcode.cn/problems/reward-top-k-students/

比较适合用于练习 语言基础语法的一道题

解法1:

模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
模拟
哈希表记录feed_back的分数 然后遍历report直接计算分数
*/
class Solution {
public:
vector<int> topStudents(vector<string>& positive_feedback, vector<string>& negative_feedback, vector<string>& report, vector<int>& student_id, int k) {
unordered_map<string,int>score;
for(int i = 0; i < positive_feedback.size() ; i++ ){
score[positive_feedback[i]] = 3;
}

for(int i = 0; i < negative_feedback.size(); i++){
score[negative_feedback[i]] = -1;
}


vector<int>s(report.size(),0);

for(int i = 0 ; i < report.size() ; i++){
int m = report[i].size();
// cout << report[i] << endl;
for(int j = 0; j < m ; ){
int k = j + 1;

while(k < m && report[i][k] != ' ' ){
k++;
}
// cout << report[i].substr(j,k - j) << endl;
// c++ unordered_map 不存在键值 直接默认值为0
s[i] += score[report[i].substr(j,k - j)];
j = k + 1;
}
}

vector<pair<int,int>>p(report.size());

for(int i = 0 ; i < report.size() ; i++){
p[i].first = s[i];
p[i].second = student_id[i];
}

sort(p.begin(),p.end(),[&](pair<int,int>a,pair<int,int>b)->bool{
if(a.first == b.first){
return a.second < b.second;
}else{
return a.first > b.first;
}
});

vector<int>ans;

for(int i = 0 ; i < k ; i++){
ans.push_back(p[i].second);
}

return ans;
}
};