[LeetCode] High Five

1086. High Five

Given a list of the scores of different students, items, where items[i] = [IDi, scorei] represents one score from a student with IDi, calculate each student’s top five average.

Return the answer as an array of pairs result, where result[j] = [IDj, topFiveAveragej] represents the student with IDj and their top five average. Sort result by IDj in increasing order.

A student’s top five average is calculated by taking the sum of their top five scores and dividing it by 5 using integer division.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<vector<int>> highFive(vector<vector<int>>& items) {
unordered_map<int, vector<int>> best;
for(auto item : items) {
best[item[0]].push_back(item[1]);
sort(rbegin(best[item[0]]), rend(best[item[0]]));
if(best[item[0]].size() > 5) best[item[0]].pop_back();
}
vector<vector<int>> res;
for(auto [k,vec] : best) {
res.push_back({k, accumulate(begin(vec), end(vec),0)/5});
}
sort(begin(res), end(res), [](auto a, auto b) {
return a[0] < b[0];
});
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/high-five/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.