- High Five
There are two properties in the node student id and scores, to ensure that each student will have at least 5 points, find the average of 5 highest scores for each person.
Example
Example 1:
Input:
[[1,91],[1,92],[2,93],[2,99],[2,98],[2,97],[1,60],[1,58],[2,100],[1,61]]
Output:
1: 72.40
2: 97.40
Example 2:
Input:
[[1,90],[1,90],[1,90],[1,90],[1,90],[1,90]]
Output:
1: 90.00
解法1:
利用min-heap,每个学生都分配要给min-heap (size = 5)。
记得最后算平均值的时候,priority-queue是不能用iterator或auto进行遍历的,只能看top(),然后pop()。C++ STL的容器里面只有vector/queue/deque/set/map之类的才能用iterator遍历,priority-queue好像不行 。
注意:
1)求前k个最大的值最好用最小堆(这样堆的size()就是k就可以了)。如果用最大堆,堆的size()要是n。
代码同步在
https://github.com/luqian2017/Algorithm
/**
* Definition for a Record
* class Record {
* public:
* int id, score;
* Record(int id, int score) {
* this->id = id;
* this->score = score;
* }
* };
*/
class Solution {
public:
/**
* @param results a list of <student_id, score>
* @return find the average of 5 highest scores for each person
* map<int, double> (student_id, average_score)
*/
map<int, double> highFive(vector<Record>& results) {
int len = results.size();
map<int, priority_queue<int, vector<int>, greater<int>> > mp; //id, min-heap
map<int, double> result; //id, average-top-five
for (int i = 0; i < len; ++i) {
int studentId = results[i].id;
int studentScore = results[i].score;
mp[studentId].push(studentScore);
//get the largest 5 elements
if (mp[studentId].size() > 5)
mp[studentId].pop();
}
for (auto m : mp) {
double sum = 0;
while(m.second.size() > 0) {
sum += m.second.top();
m.second.pop();
}
result[m.first] = sum / 5; //strictly speacking, it needs to check if the student has >= 5 courses
}
return result;
}
};