Design a Leaderboard class, which has 3 functions:
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.
top(K): Return the score sum of the top K players.
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.
It's guaranteed that K is less than or equal to the current number of players.
1 <= score <= 100
There will be at most 1000 function calls.
Solutions
Solution 1: Hash Table + Ordered List
We use a hash table $d$ to record the scores of each player, and an ordered list $rank$ to record the scores of all players.
When the addScore function is called, we first check if the player is in the hash table $d$. If not, we add their score to the ordered list $rank$. Otherwise, we first remove their score from the ordered list $rank$, then add their updated score to the ordered list $rank$, and finally update the score in the hash table $d$. The time complexity is $O(\log n)$.
When the top function is called, we directly return the sum of the first $K$ elements in the ordered list $rank$. The time complexity is $O(K \times \log n)$.
When the reset function is called, we first remove the player from the hash table $d$, then remove their score from the ordered list $rank$. The time complexity is $O(\log n)$.
The space complexity is $O(n)$, where $n$ is the number of players.
fromsortedcontainersimportSortedListclassLeaderboard:def__init__(self):self.d=defaultdict(int)self.rank=SortedList()defaddScore(self,playerId:int,score:int)->None:ifplayerIdnotinself.d:self.d[playerId]=scoreself.rank.add(score)else:self.rank.remove(self.d[playerId])self.d[playerId]+=scoreself.rank.add(self.d[playerId])deftop(self,K:int)->int:returnsum(self.rank[-K:])defreset(self,playerId:int)->None:self.rank.remove(self.d.pop(playerId))# Your Leaderboard object will be instantiated and called as such:# obj = Leaderboard()# obj.addScore(playerId,score)# param_2 = obj.top(K)# obj.reset(playerId)
classLeaderboard{privateMap<Integer,Integer>d=newHashMap<>();privateTreeMap<Integer,Integer>rank=newTreeMap<>((a,b)->b-a);publicLeaderboard(){}publicvoidaddScore(intplayerId,intscore){d.merge(playerId,score,Integer::sum);intnewScore=d.get(playerId);if(newScore!=score){rank.merge(newScore-score,-1,Integer::sum);}rank.merge(newScore,1,Integer::sum);}publicinttop(intK){intans=0;for(vare:rank.entrySet()){intscore=e.getKey(),cnt=e.getValue();cnt=Math.min(cnt,K);ans+=score*cnt;K-=cnt;if(K==0){break;}}returnans;}publicvoidreset(intplayerId){intscore=d.remove(playerId);if(rank.merge(score,-1,Integer::sum)==0){rank.remove(score);}}}/** * 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); */
classLeaderboard{public:Leaderboard(){}voidaddScore(intplayerId,intscore){d[playerId]+=score;intnewScore=d[playerId];if(newScore!=score){rank.erase(rank.find(newScore-score));}rank.insert(newScore);}inttop(intK){intans=0;for(auto&x:rank){ans+=x;if(--K==0){break;}}returnans;}voidreset(intplayerId){intscore=d[playerId];d.erase(playerId);rank.erase(rank.find(score));}private:unordered_map<int,int>d;multiset<int,greater<int>>rank;};/** * 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); */
usestd::collections::BTreeMap;#[allow(dead_code)]structLeaderboard{/// This also keeps track of the top K players since it's implicitly sortedrecord_map:BTreeMap<i32,i32>,}implLeaderboard{#[allow(dead_code)]fnnew()->Self{Self{record_map:BTreeMap::new(),}}#[allow(dead_code)]fnadd_score(&mutself,player_id:i32,score:i32){ifself.record_map.contains_key(&player_id){// The player exists, just add the scoreself.record_map.insert(player_id,self.record_map.get(&player_id).unwrap()+score);}else{// Add the new player to the mapself.record_map.insert(player_id,score);}}#[allow(dead_code)]fntop(&self,k:i32)->i32{letmutcur_vec:Vec<(i32,i32)>=self.record_map.iter().map(|(k,v)|(*k,*v)).collect();cur_vec.sort_by(|lhs,rhs|rhs.1.cmp(&lhs.1));// Iterate reversely for Kletmutsum=0;letmuti=0;for(_,value)in&cur_vec{ifi==k{break;}sum+=value;i+=1;}sum}#[allow(dead_code)]fnreset(&mutself,player_id:i32){// The player is ensured to exist in the board// Just set the score to 0self.record_map.insert(player_id,0);}}