每个学生有两个属性
id和scores。找到每个学生最高的5个分数的平均值。
样例
给出 results = [[1,91],[1,92],[2,93],[2,99],[2,98],[2,97],[1,60],[1,58],[2,100],[1,61]]
返回:
1: 72.40
2: 97.40
思路
topK问题,K等于5
代码
/**
* Definition for a Record
* class Record {
* public int id, score;
* public Record(int id, int score){
* this.id = id;
* this.score = score;
* }
* }
*/
public class Solution {
/**
* @param results a list of <student_id, score>
* @return find the average of 5 highest scores for each person
* Map<Integer, Double> (student_id, average_score)
*/
public Map<Integer, Double> highFive(Record[] results) {
Map<Integer, Double> answer = new HashMap<Integer, Double>();
Map<Integer, PriorityQueue<Integer>> hash = new HashMap<Integer, PriorityQueue<Integer>>();
for (Record r : results) {
if (!hash.containsKey(r.id)){
hash.put(r.id, new PriorityQueue<Integer>());
}
// PriorityQueue里存的是scores;
PriorityQueue<Integer> pq = hash.get(r.id);
// PriorityQueue里数量不足5个直接加进去
if (pq.size() < 5) {
pq.add(r.score);
// PriorityQueue里够5个了,和最小的比较,不行的淘汰
} else {
if (pq.peek() < r.score){
pq.poll();
pq.add(r.score);
}
}
}
for (Map.Entry<Integer, PriorityQueue<Integer>> entry : hash.entrySet()) {
int id = entry.getKey();
PriorityQueue<Integer> scores = entry.getValue();
double average = 0;
for (int i = 0; i < 5; ++i)
average += scores.poll();
average /= 5.0;
answer.put(id, average);
}
return answer;
}
}
