|
12 | 12 |
|
13 | 13 | <ol> |
14 | 14 | <li><code>addScore(playerId, score)</code>: |
15 | | - |
16 | 15 | <ul> |
17 | 16 | <li>假如参赛者已经在排行榜上,就给他的当前得分增加 <code>score</code> 点分值并更新排行。</li> |
18 | 17 | <li>假如该参赛者不在排行榜上,就把他添加到榜单上,并且将分数设置为 <code>score</code>。</li> |
@@ -60,27 +59,82 @@ leaderboard.top(3); // returns 141 = 51 + 51 + 39; |
60 | 59 | <li>最多进行 <code>1000</code> 次函数调用</li> |
61 | 60 | </ul> |
62 | 61 |
|
63 | | - |
64 | 62 | ## 解法 |
65 | 63 |
|
66 | 64 | <!-- 这里可写通用的实现逻辑 --> |
67 | 65 |
|
| 66 | +用哈希表存放每个 playerId 所对应的分数。 |
| 67 | + |
| 68 | +计算 topK 时,取出所有的分数,进行排序,获取前 K 个分数,累加得到结果。 |
| 69 | + |
68 | 70 | <!-- tabs:start --> |
69 | 71 |
|
70 | 72 | ### **Python3** |
71 | 73 |
|
72 | 74 | <!-- 这里可写当前语言的特殊实现逻辑 --> |
73 | 75 |
|
74 | 76 | ```python |
| 77 | +class Leaderboard: |
| 78 | + |
| 79 | + def __init__(self): |
| 80 | + self.player_scores = {} |
75 | 81 |
|
| 82 | + def addScore(self, playerId: int, score: int) -> None: |
| 83 | + self.player_scores[playerId] = self.player_scores.get(playerId, 0) + score |
| 84 | + |
| 85 | + def top(self, K: int) -> int: |
| 86 | + scores = sorted(list(self.player_scores.values()), reverse=True) |
| 87 | + return sum(scores[:K]) |
| 88 | + |
| 89 | + def reset(self, playerId: int) -> None: |
| 90 | + self.player_scores[playerId] = 0 |
| 91 | + |
| 92 | + |
| 93 | +# Your Leaderboard object will be instantiated and called as such: |
| 94 | +# obj = Leaderboard() |
| 95 | +# obj.addScore(playerId,score) |
| 96 | +# param_2 = obj.top(K) |
| 97 | +# obj.reset(playerId) |
76 | 98 | ``` |
77 | 99 |
|
78 | 100 | ### **Java** |
79 | 101 |
|
80 | 102 | <!-- 这里可写当前语言的特殊实现逻辑 --> |
81 | 103 |
|
82 | 104 | ```java |
83 | | - |
| 105 | +class Leaderboard { |
| 106 | + private Map<Integer, Integer> playerScores; |
| 107 | + |
| 108 | + public Leaderboard() { |
| 109 | + playerScores = new HashMap<>(); |
| 110 | + } |
| 111 | + |
| 112 | + public void addScore(int playerId, int score) { |
| 113 | + playerScores.put(playerId, playerScores.getOrDefault(playerId, 0) + score); |
| 114 | + } |
| 115 | + |
| 116 | + public int top(int K) { |
| 117 | + List<Integer> scores = new ArrayList<>(playerScores.values()); |
| 118 | + Collections.sort(scores, Collections.reverseOrder()); |
| 119 | + int res = 0; |
| 120 | + for (int i = 0; i < K; ++i) { |
| 121 | + res += scores.get(i); |
| 122 | + } |
| 123 | + return res; |
| 124 | + } |
| 125 | + |
| 126 | + public void reset(int playerId) { |
| 127 | + playerScores.put(playerId, 0); |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +/** |
| 132 | + * Your Leaderboard object will be instantiated and called as such: |
| 133 | + * Leaderboard obj = new Leaderboard(); |
| 134 | + * obj.addScore(playerId,score); |
| 135 | + * int param_2 = obj.top(K); |
| 136 | + * obj.reset(playerId); |
| 137 | + */ |
84 | 138 | ``` |
85 | 139 |
|
86 | 140 | ### **...** |
|
0 commit comments