|
| 1 | +class Leaderboard { |
| 2 | + Map<Integer, Integer> scoreMap; |
| 3 | + Map<Integer, Set<Integer>> playerMap; |
| 4 | + public Leaderboard() { |
| 5 | + scoreMap = new HashMap<>(); |
| 6 | + playerMap = new TreeMap<>(Collections.reverseOrder()); |
| 7 | + } |
| 8 | + |
| 9 | + public void addScore(int playerId, int score) { |
| 10 | + if (scoreMap.containsKey(playerId)) { |
| 11 | + int prevScore = scoreMap.get(playerId); |
| 12 | + playerMap.get(prevScore).remove(playerId); |
| 13 | + } |
| 14 | + scoreMap.put(playerId, scoreMap.getOrDefault(playerId, 0) + score); |
| 15 | + playerMap.computeIfAbsent(scoreMap.get(playerId), k -> new HashSet<>()).add(playerId); |
| 16 | + } |
| 17 | + |
| 18 | + public int top(int K) { |
| 19 | + int sum = 0; |
| 20 | + for (Integer key : playerMap.keySet()) { |
| 21 | + int count = Math.min(K, playerMap.get(key).size()); |
| 22 | + sum += key * count; |
| 23 | + K -= count; |
| 24 | + if (K == 0) { |
| 25 | + break; |
| 26 | + } |
| 27 | + } |
| 28 | + return sum; |
| 29 | + } |
| 30 | + |
| 31 | + public void reset(int playerId) { |
| 32 | + int prevScore = scoreMap.get(playerId); |
| 33 | + playerMap.get(prevScore).remove(playerId); |
| 34 | + scoreMap.put(playerId, 0); |
| 35 | + playerMap.computeIfAbsent(0, k -> new HashSet<>()).add(playerId); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Your Leaderboard object will be instantiated and called as such: |
| 41 | + * Leaderboard obj = new Leaderboard(); |
| 42 | + * obj.addScore(playerId,score); |
| 43 | + * int param_2 = obj.top(K); |
| 44 | + * obj.reset(playerId); |
| 45 | + */ |
0 commit comments