数组“分数”表示参与比赛的每个人的总分。例如:
User A: 100 points
User B: 90 points
User C: 90 points
User D: 80 points
User E: 75 points
User F: 60 points
根据上面的分数,我们会有这个排名:
User A: #1
User B: #2
User C: #2
User D: #3
User E: #4
User F: #5
这种排名方法遵循密集排名方法。
然后我们有一个名为 alice 的用户。如果她得到 55 分,她将排在第 6 位(根据上面的排名)。如果她获得 90 分,她将排在第 2 位。等等。
我实际上有一个包含爱丽丝不同“会话”的数组。例如:
[55, 90]
这意味着爱丽丝第一次将排在第 6 位。而第二次她将排名第二。
我对此进行了编码,并且可以正常工作。但是,这似乎不是很有效。对于分数数组中有 50 万个条目的大型数据集,它会超时。这是代码:
const getPosition = (element, scores) => {
scores.push(element);
scores.sort(function (a,b) { return b-a; });
return scores.indexOf(element)+1;
}
function climbingLeaderboard(scores, alice) {
var uniqueSet = new Set(scores);
scores = [...uniqueSet];
var positions = [];
let aliceIndex = 0;
while(aliceIndex < alice.length){
positions.push(getPosition(alice[aliceIndex], scores));
aliceIndex++;
}
return positions;
}
function main() {
const scores = [100, 90, 90, 80, 75, 60];
const alice = [50, 65, 77, 90, 102];
let result = climbingLeaderboard(scores, alice);
console.log(result.join("\n") + "\n");
}
我猜“排序”功能和/或使用 indexOf 搜索数组中的元素是问题所在。但是我找不到让这两个操作更高效的方法。
浮云间
狐的传说
郎朗坤
相关分类