Skip to content

Commit 9857a6b

Browse files
author
zongyanqi
committed
add Easy_506_Relative_Ranks
1 parent b91bfe0 commit 9857a6b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Easy_506_Relative_Ranks.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 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".
3+
4+
Example 1:
5+
Input: [5, 4, 3, 2, 1]
6+
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
7+
Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
8+
For the left two athletes, you just need to output their relative ranks according to their scores.
9+
Note:
10+
N is a positive integer and won't exceed 10,000.
11+
All the scores of athletes are guaranteed to be unique.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @return {string[]}
17+
*/
18+
var findRelativeRanks = function (nums) {
19+
20+
var medals = ["Gold Medal", "Silver Medal", "Bronze Medal"];
21+
var ranks = [];
22+
Array.prototype.push.apply(ranks, nums);
23+
ranks.sort(function (a, b) {
24+
return b - a;
25+
});
26+
27+
return nums.map((n) => {
28+
var rank = ranks.indexOf(n);
29+
return medals[rank] || (rank + 1) + '';
30+
});
31+
};
32+
33+
// ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
34+
console.log(findRelativeRanks([10, 3, 8, 9, 4]));
35+
36+
console.log(findRelativeRanks([5, 4, 1, 2, 3]));

0 commit comments

Comments
 (0)