Lintcode阶梯训练~算法

优秀成绩

2017-07-03  本文已影响22人  lyoungzzz

描述

每个学生有两个属性 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

代码实现

/**
 * 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> answers = new HashMap<>();
        Map<Integer, PriorityQueue<Integer>> hash = new HashMap<>();
        
        for (Record r : results) {
            if(!hash.containsKey(r.id)) {
                hash.put(r.id, new PriorityQueue<Integer>()); 
            }
            //不能加else,否则id第一次加出现入的数组中的成绩无法加入队列中
            //else {
            //这里的else可以的原因是if语句进行了第二次判断,由于第一次
            //加入了,如果原本hash不中存在的,此时肯定存在,便会将成绩加入队列
            //当然也可以省去这里的if语句
            if (hash.containsKey(r.id)) {   
                PriorityQueue<Integer> pq = hash.get(r.id);
                if (pq.size() < 5) {
                    pq.add(r.score);
                } else {
                    if (pq.peek() < r.score) {
                        pq.poll();
                        pq.add(r.score); 
                    }
                }
            }
        }
        //Map.Entry是Map的嵌套类
        // 使用Map.Entry是为了获取每次遍历时map的key和value,map没有该方法的实现
        //hash.entrySet()是为了匹配Map.Entry
        for (Map.Entry<Integer, PriorityQueue<Integer>> map : hash.entrySet()) {
            int id = map.getKey();
            PriorityQueue<Integer> score = map.getValue();
            double average = 0;
            for (int i = 0; i < 5; i++) {
                average += score.poll();
            }
                average /=  5.0;
                answers.put(id, average);
        }
        return answers;
        
    }
}
上一篇下一篇

猜你喜欢

热点阅读