|
| 1 | +/** |
| 2 | + * 1244. Design A Leaderboard |
| 3 | + * https://leetcode.com/problems/design-a-leaderboard/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Design a Leaderboard class, which has 3 functions: |
| 7 | + * - addScore(playerId, score): Update the leaderboard by adding score to the given player's |
| 8 | + * score. If there is no player with such id in the leaderboard, add him to the leaderboard |
| 9 | + * with the given score. |
| 10 | + * - top(K): Return the score sum of the top K players. |
| 11 | + * - reset(playerId): Reset the score of the player with the given id to 0 (in other words |
| 12 | + * erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard |
| 13 | + * before calling this function. |
| 14 | + * |
| 15 | + * Initially, the leaderboard is empty. |
| 16 | + */ |
| 17 | + |
| 18 | + |
| 19 | +var Leaderboard = function() { |
| 20 | + this.scores = new Map(); |
| 21 | +}; |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number} playerId |
| 25 | + * @param {number} score |
| 26 | + * @return {void} |
| 27 | + */ |
| 28 | +Leaderboard.prototype.addScore = function(playerId, score) { |
| 29 | + this.scores.set(playerId, (this.scores.get(playerId) || 0) + score); |
| 30 | +}; |
| 31 | + |
| 32 | +/** |
| 33 | + * @param {number} K |
| 34 | + * @return {number} |
| 35 | + */ |
| 36 | +Leaderboard.prototype.top = function(K) { |
| 37 | + const sortedScores = Array.from(this.scores.values()).sort((a, b) => b - a); |
| 38 | + return sortedScores.slice(0, K).reduce((sum, score) => sum + score, 0); |
| 39 | +}; |
| 40 | + |
| 41 | +/** |
| 42 | + * @param {number} playerId |
| 43 | + * @return {void} |
| 44 | + */ |
| 45 | +Leaderboard.prototype.reset = function(playerId) { |
| 46 | + this.scores.delete(playerId); |
| 47 | +}; |
0 commit comments