[LeetCode] Design A Leaderboard

1244. Design A Leaderboard

Design a Leaderboard class, which has 3 functions:

  1. addScore(playerId, score): Update the leaderboard by adding score 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 score.
  2. top(K): Return the score sum of the top K players.
  3. reset(playerId): 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Leaderboard {
unordered_map<int, int> m;
public:
Leaderboard() {

}

void addScore(int p, int s) {
m[p] += s;
}

int top(int K) {
vector<pair<int, int>> topK(K);
partial_sort_copy(begin(m),end(m),begin(topK),end(topK),[](const pair<const int, int>& p1, const pair<const int, int>& p2) { return p1.second > p2.second; });
int res(0);
for(auto& t : topK) res += t.second;
return res;
}

void reset(int p) {
m[p] = 0;
}
};

/**
* Your Leaderboard object will be instantiated and called as such:
* Leaderboard* obj = new Leaderboard();
* obj->addScore(playerId,score);
* int param_2 = obj->top(K);
* obj->reset(playerId);
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Leaderboard {
unordered_map<int, int> m;
multiset<int> ms;
public:
Leaderboard() {

}

void addScore(int p, int s) {
auto it = ms.find(m[p]);
if(it != ms.end()) ms.erase(it);
m[p] += s;
ms.insert(m[p]);
}

int top(int K) {
int res(0), i(0);
for(auto it = ms.rbegin(); it != ms.rend() && i < K; it++) {
res += *it; i++;
}
return res;
}

void reset(int p) {
auto it = ms.find(m[p]);
if(it != ms.end()) ms.erase(it);
m[p] = 0;
}
};

/**
* Your Leaderboard object will be instantiated and called as such:
* Leaderboard* obj = new Leaderboard();
* obj->addScore(playerId,score);
* int param_2 = obj->top(K);
* obj->reset(playerId);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/design-a-leaderboard/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.