613. 优秀成绩

描述

每个学生有两个属性idscores。找到每个学生最高的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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 【1】7,9,-1,5,( ) A、4;B、2;C、-1;D、-3 分析:选D,7+9=16;9+(-1)=8;(...
    Alex_bingo阅读 19,502评论 1 19
  • 每条河流都有一个梦想:奔向大海。长江、黄河都奔向了大海,方式不一样。长江劈山开路,黄河迂回曲折,轨迹不一样,但都有...
    尹智强阅读 1,839评论 0 2
  • 毕业后,因为种种不切实际的期望而选择留在大城市,可最后的最后却终究是竹篮打水一场空,不知道如何去形容倾注的所有希望...
    最好的年纪阅读 5,544评论 0 0
  • 演讲要从自身的练习开始,还要克服紧张的气氛,注意演讲的情绪互动,在演讲中加入提问的形式,演讲就像是讲故事。
    临淄茂业DDM王春梅阅读 884评论 0 0
  • 《寻找灵感》(组诗) 诗/陈述 (一) 古老的方式已经长成了笔直的大树 连接着天与地。河流在不断地 寻找低处,带来...
    诗人陈述阅读 3,599评论 20 15