Problem
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.
Example
Given results = [[1,91],[1,92],[2,93],[2,99],[2,98],[2,97],[1,60],[1,58],[2,100],[1,61]]
Return
思路
- 求每个人的top 5, 于是需要一个hash table
public Map<Integer, Double> highFive(Record[] results) {
Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();
Map<Integer, Double> res = new HashMap<>();
if (results == null || results.length == 0) {
return res;
}
for (Record r: results) {
if (!map.containsKey(r.id)) {
map.put(r.id, new PriorityQueue<Integer>());
}
PriorityQueue<Integer> heap = map.get(r.id);
heap.offer(r.score);
if (heap.size() > 5) {
heap.poll();
}
}
for (Integer key: map.keySet()) {
double sum = 0;
for (Integer s: map.get(key)) {
sum += s;
}
res.put(key, sum / 5);
}
return res;
}