-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1244_Design-A-Leaderboard.cpp
More file actions
91 lines (78 loc) · 2.2 KB
/
1244_Design-A-Leaderboard.cpp
File metadata and controls
91 lines (78 loc) · 2.2 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Hash Map + Hash Set
class Leaderboard {
public:
unordered_map<int,int> scoreMap;
set<pair<int,int>> rankBoard;
Leaderboard() {}
void addScore(int playerId, int score) {
if(scoreMap.count(playerId)){
rankBoard.erase({scoreMap[playerId], playerId});
}
scoreMap[playerId] += score;
rankBoard.insert({scoreMap[playerId], playerId});
}
int top(int K) {
int sum = 0;
auto it = rankBoard.rbegin();
while(K && it != rankBoard.rend()){
sum += it->first;
--K;
++it;
}
return sum;
}
void reset(int playerId) {
int score = scoreMap[playerId];
rankBoard.erase({score, playerId});
scoreMap.erase(playerId);
}
};
/**
* 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);
*/
// Priority Queue + Hash Map with lazy update
class Leaderboard {
public:
priority_queue<pair<int,int>> pq;
unordered_map<int, int> scoreMap;
Leaderboard() {}
void addScore(int playerId, int score) {
int accScore = scoreMap[playerId] + score;
scoreMap[playerId] = accScore;
pq.push({accScore, playerId});
}
int top(int K) {
stack<pair<int,int>> tempStack;
unordered_set<int> visited;
int topKSum = 0;
while(!pq.empty() && K){
auto [score, player] = pq.top();
pq.pop();
if(!visited.count(player) && score == scoreMap[player]){
visited.insert(player);
tempStack.push({score, player});
topKSum += score;
--K;
}
}
while(!tempStack.empty()){
pq.push(tempStack.top());
tempStack.pop();
}
return topKSum;
}
void reset(int playerId) {
scoreMap[playerId] = 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);
*/