High Five

Given a list of scores of different students, return the average score of each student's top five scores in the order of each student's id.

Each entry items[i] has items[i][0] the student's id, and items[i][1] the student's score.  The average score is calculated using integer division.

Example 1:

Input: [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
Output: [[1,87],[2,88]]
Explanation: 
The average of the student with id = 1 is 87.
The average of the student with id = 2 is 88.6. But with integer division their average converts to 88.

思路:就是一个hashmap统计和priorityqueue统计top k

class Solution {
    
    private class Node {
        public int id;
        public int average;
        public Node(int id, int average) {
            this.id = id;
            this.average = average;
        }
    }
    private class NodeComparator implements Comparator<Node> {
        @Override
        public int compare(Node a, Node b) {
            return a.id - b.id;
        }
    }
    public int[][] highFive(int[][] items) {
        if(items == null || items.length == 0 || items[0].length == 0) {
            return new int[0][0];
        }
        HashMap<Integer, PriorityQueue<Integer>> hashmap = new HashMap<>();
        for(int i = 0; i < items.length; i++) {
            int id = items[i][0];
            int score = items[i][1];
            hashmap.putIfAbsent(id, new PriorityQueue<Integer>());
            if(hashmap.get(id).size() < 5) {
                hashmap.get(id).add(score);
            } else{
                if(hashmap.get(id).peek() < score) {
                    hashmap.get(id).poll();
                    hashmap.get(id).add(score);
                }
            }
        }
        List<Node> list = new ArrayList<Node>();
        int index = 0;
        for(Integer key: hashmap.keySet()) {
            int average = calculate(hashmap.get(key));
            list.add(new Node(key, average));
        }
        Collections.sort(list, new NodeComparator());
        int[][] result = new int[list.size()][2];
        for(int i = 0; i < list.size(); i++) {
            result[i][0] = list.get(i).id;
            result[i][1] = list.get(i).average;
        }
        return result;
    }
    
    private int calculate(PriorityQueue<Integer> pq) {
        int sum = 0;
        while(!pq.isEmpty()) {
            Integer integer = pq.poll();
            sum += integer.intValue();
        }
        return sum / 5;
    }
}
发布了663 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104751388