Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: “Gold Medal”, “Silver Medal” and “Bronze Medal”.
var findRelativeRanks = function(nums) {
var res = [];
var tmp = [];
var obj = {};
tmp = nums.slice();
tmp.sort(function(a,b) {return b - a})
obj[tmp[0]] = 'Gold Medal';
obj[tmp[1]] = 'Silver Medal';
obj[tmp[2]] = 'Bronze Medal';
for(var m = 3; m < tmp.length; m++) {
obj[tmp[m]] = m + 1 + ''
}
for(var j = 0; j < nums.length; j++) {
res.push(obj[nums[j]])
}
return res
};
本文介绍了一种算法,该算法接收一组运动员的成绩,并返回每个运动员的相对排名及成绩最高的前三名运动员所获得的“金牌”、“银牌”和“铜牌”。通过将成绩从高到低排序并为前三名分配特定的奖牌,然后为其余运动员分配其排名,实现了这一功能。

被折叠的 条评论
为什么被折叠?



