July 24, 2022

1244. Design A Leaderboard

1244. Design A Leaderboard

HashMap + Heap

class Leaderboard {
    Map<Integer, Integer> map;

    public Leaderboard() {
        map = new HashMap<>();
    }
    
    public void addScore(int playerId, int score) {
        if (map.containsKey(playerId)) {
            map.put(playerId, map.get(playerId) + score);
        } else {
            map.put(playerId, score);
        }
    }
    
    public int top(int K) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(K);
        for (int key : map.keySet()) {
            int value = map.get(key);
            minHeap.offer(value);
            if (minHeap.size() > K) {
                minHeap.poll();
            }
        }
        int sum = 0;
        while (!minHeap.isEmpty()) {
            sum += minHeap.poll();
        }
        return sum;
    }
    
    public void reset(int playerId) {
        map.remove(playerId);
    }
}

/**
 * Your Leaderboard object will be instantiated and called as such:
 * Leaderboard obj = new Leaderboard();
 * obj.addScore(playerId,score);
 * int param_2 = obj.top(K);
 * obj.reset(playerId);
 */
comments powered by Disqus