新一轮的「力扣杯」编程大赛即将启动,为了动态显示参赛者的得分数据,需要设计一个排行榜 Leaderboard。
请你帮忙来设计这个 Leaderboard 类,使得它有如下 3 个函数:
addScore(playerId, score): 假如参赛者已经在排行榜上,就给他的当前得分增加 score 点分值并更新排行。 假如该参赛者不在排行榜上,就把他添加到榜单上,并且将分数设置为 score。 top(K):返回前 K 名参赛者的 得分总和。 reset(playerId):将指定参赛者的成绩清零(换句话说,将其从排行榜中删除)。题目保证在调用此函数前,该参赛者已有成绩,并且在榜单上。
请注意,在初始状态下,排行榜是空的。
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/design-a-leaderboard
这是今天刷到的一个算法题,比较简单
说白了就是简单的增删改查,唯一不能直接出结果的就是排名,我用的是类存成绩,转换排行的时候变成数组
var Leaderboard = function() {
this.bang = {}
};
/**
* @param {number} playerId
* @param {number} score
* @return {void}
*/
Leaderboard.prototype.addScore = function(playerId, score) {
this.bang[playerId] = this.bang[playerId]==undefined?0:this.bang[playerId]
this.bang[playerId]+=score
};
/**
* @param {number} K
* @return {number}
*/
Leaderboard.prototype.top = function(K) {
let num = []
for(let i in this.bang){
num.push(this.bang[i])
}
num.sort((a,b)=>b-a)
let k =0
for(let i=0;i<K;i++){
k+=num[i]
}
return k
};
/**
* @param {number} playerId
* @return {void}
*/
Leaderboard.prototype.reset = function(playerId) {
delete this.bang[playerId]
};
/**
* Your Leaderboard object will be instantiated and called as such:
* var obj = new Leaderboard()
* obj.addScore(playerId,score)
* var param_2 = obj.top(K)
* obj.reset(playerId)
*/
不得不说,开了会员以后,算的是快