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 题目总结