LeetCode 1244. 力扣排行榜

地址 https://www.acwing.com/solution/LeetCode/content/5765/算法

題目描述
新一輪的「力扣杯」編程大賽即將啓動,爲了動態顯示參賽者的得分數據,須要設計一個排行榜 Leaderboard。編程

請你幫忙來設計這個 Leaderboard 類,使得它有以下 3 個函數:ide

addScore(playerId, score):
假如參賽者已經在排行榜上,就給他的當前得分增長 score 點分值並更新排行。
假如該參賽者不在排行榜上,就把他添加到榜單上,而且將分數設置爲 score。
top(K):返回前 K 名參賽者的 得分總和。
reset(playerId):將指定參賽者的成績清零。題目保證在調用此函數前,該參賽者已有成績,而且在榜單上。
請注意,在初始狀態下,排行榜是空的函數

輸入: 
["Leaderboard","addScore","addScore","addScore","addScore","addScore","top","reset","reset","addScore","top"]
[[],[1,73],[2,56],[3,39],[4,51],[5,4],[1],[1],[2],[2,51],[3]]
輸出:
[null,null,null,null,null,null,73,null,null,null,141]

解釋: 
Leaderboard leaderboard = new Leaderboard ();
leaderboard.addScore(1,73);   // leaderboard = [[1,73]];
leaderboard.addScore(2,56);   // leaderboard = [[1,73],[2,56]];
leaderboard.addScore(3,39);   // leaderboard = [[1,73],[2,56],[3,39]];
leaderboard.addScore(4,51);   // leaderboard = [[1,73],[2,56],[3,39],[4,51]];
leaderboard.addScore(5,4);    // leaderboard = [[1,73],[2,56],[3,39],[4,51],[5,4]];
leaderboard.top(1);           // returns 73;
leaderboard.reset(1);         // leaderboard = [[2,56],[3,39],[4,51],[5,4]];
leaderboard.reset(2);         // leaderboard = [[3,39],[4,51],[5,4]];
leaderboard.addScore(2,51);   // leaderboard = [[2,51],[3,39],[4,51],[5,4]];
leaderboard.top(3);           // returns 141 = 51 + 51 + 39;

算法1
這道題目 我感受更像系統設計題
因爲須要依靠ID快速查找對應分數 而且分數還須要快速排序,因此我以爲應該 須要兩個容器去進行存儲,應對不一樣的需求。
查找固然是哈希,排序的話因爲分數不是惟一的,我採起的是vector
那麼對記錄進行增刪改的時候 就須要對兩個容器進行操做spa

C++ 代碼設計

 1 class Leaderboard {
 2 public:
 3     vector<int> scoreVec;
 4     map<int, int> idScore;
 5     Leaderboard() {
 6         scoreVec.clear();
 7         idScore.clear();
 8     }
 9 
10     void addScore(int playerId, int score) {
11         if (idScore.count(playerId) != 0) {
12             int oldscore = idScore[playerId];
13             idScore[playerId] += score;
14             vector<int>::iterator it = find(scoreVec.begin(), scoreVec.end(), oldscore);
15             *it += score;
16         }
17         else {
18             idScore[playerId] = score;
19             scoreVec.push_back(score);
20         }
21     }
22 
23     int top(int K) {
24         sort(scoreVec.begin(), scoreVec.end(),greater<int>());
25         int sum = 0;
26         for (int i = 0; i < scoreVec.size() && i < K; i++) {
27             sum += scoreVec[i];
28         }
29         return sum;
30     }
31 
32     void reset(int playerId) {
33         int score = idScore[playerId];
34         idScore.erase(playerId);
35         vector<int>::iterator it = find(scoreVec.begin(), scoreVec.end(), score);
36         scoreVec.erase(it);
37     }
38 };
View Code
相關文章
相關標籤/搜索