[LeetCode] Reward Top K Students

2512. Reward Top K Students

You are given two string arrays positive_feedback and negative_feedback, containing the words denoting positive and negative feedback, respectively. Note that no word is both positive and negative.

Initially every student has 0 points. Each positive word in a feedback report increases the points of a student by 3, whereas each negative word decreases the points by 1.

You are given n feedback reports, represented by a 0-indexed string array report and a 0-indexed integer array student_id, where student_id[i] represents the ID of the student who has received the feedback report report[i]. The ID of each student is unique.

Given an integer k, return the top k students after ranking them in non-increasing order by their points. In case more than one student has the same points, the one with the lower ID ranks higher.

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
class Solution {
string parse(string& s, int& p) {
if(s[p] == ' ') p += 1;
string res = "";
while(p < s.length() and s[p] != ' ') res.push_back(s[p++]);
return res;
}
public:
vector<int> topStudents(vector<string>& A, vector<string>& B, vector<string>& report, vector<int>& id, int k) {
unordered_set<string> pos(begin(A), end(A));
unordered_set<string> neg(begin(B), end(B));
unordered_map<int,int> mp;
for(int i = 0; i < id.size(); i++) {
int now = 0, p = 0;
while(p < report[i].size()) {
auto token = parse(report[i], p);
if(pos.count(token)) now += 3;
if(neg.count(token)) now -= 1;
}
mp[id[i]] += now;
}
vector<pair<int,int>> rank;
for(auto [k,v] : mp) rank.push_back({v,k});
sort(begin(rank), end(rank), [](auto a, auto b) {
if(a.first == b.first) return a.second < b.second;
return a.first > b.first;
});
vector<int> res;
for(int i = 0; i < k; i++) {
res.push_back(rank[i].second);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/25/PS/LeetCode/reward-top-k-students/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.