Design a Leaderboard class, which has 3 functions:
<code>addScore(playerId, score)</code>: Update the leaderboard by adding <code>score</code> to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the given <code>score</code>.
<code>top(K)</code>: Return the score sum of the top <code>K</code> players.
<code>reset(playerId)</code>: Reset the score of the player with the given id to 0 (in other words erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard before calling this function.
Initially, the leaderboard is empty.
Example 1:
Constraints:
<code>1 <= playerId, K <= 10000</code>
It's guaranteed that <code>K</code> is less than or equal to the current number of players.
<code>1 <= score <= 100</code>
There will be at most <code>1000</code> function calls.
力扣排行榜。
新一輪的「力扣杯」程式設計大賽即将啟動,為了動态顯示參賽者的得分資料,需要設計一個排行榜 Leaderboard。 請你幫忙來設計這個 Leaderboard 類,使得它有如下 3 個函數: addScore(playerId, score): 假如參賽者已經在排行榜上,就給他的目前得分增加 score 點分值并更新排行。 假如該參賽者不在排行榜上,就把他添加到榜單上,并且将分數設定為 score。 top(K):傳回前 K 名參賽者的 得分總和。 reset(playerId):将指定參賽者的成績清零(換句話說,将其從排行榜中删除)。題目保證在調用此函數前,該參賽者已有成績,并且在榜單上。 請注意,在初始狀态下,排行榜是空的。 來源:力扣(LeetCode) 連結:https://leetcode-cn.com/problems/design-a-leaderboard 著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
這是一道設計題。我的思路如下,我們需要一個hashmap,一個treemap。除了題目要求實作的函數之外,我還需要一個helper函數。他的作用是當某一個player的分數有變動的時候,我需要将對應unique score記錄的player的個數做出修改。其餘部分參見代碼。
hashmap - <playerId, his/her score>
treemap - <each unique score, how many people have this same score>
時間O(n)
空間O(n)
Java實作
LeetCode 題目總結