There are two properties in the node studentidandscores, to ensure that each student will have at least 5 points, find the average of 5 highest scores for each person.

Have you met this question in a real interview?

Yes

Example

Given results = [[1,91],[1,92],[2,93],[2,99],[2,98],[2,97],[1,60],[1,58],[2,100],[1,61]]

Return
/**
 * 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) {
        // Write your code here
        map<int, double> res;
        unordered_map<int, priority_queue<int, vector<int>, greater<int>>> hash;
        for (Record& rec : results) {
            auto& pq = hash[rec.id];
            pq.push(rec.score);
            if (pq.size() > 5) {
                pq.pop();
            }
        }
        for (auto& it : hash) {
            res[it.first] = average(it.second);
        }
        return res;
    }

    double average(priority_queue<int, vector<int>, greater<int>> &pq) {
        double res = 0;
        int sum = 0;
        while (!pq.empty()) {
            sum += pq.top();
            pq.pop();
        }
        res = sum / 5.0;
        return res;
    }
};

results matching ""

    No results matching ""