|
| 1 | +/** |
| 2 | + * 506. Relative Ranks |
| 3 | + * https://leetcode.com/problems/relative-ranks/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * You are given an integer array score of size n, where score[i] is the score of the ith |
| 7 | + * athlete in a competition. All the scores are guaranteed to be unique. |
| 8 | + * |
| 9 | + * The athletes are placed based on their scores, where the 1st place athlete has the highest |
| 10 | + * score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each |
| 11 | + * athlete determines their rank: |
| 12 | + * - The 1st place athlete's rank is "Gold Medal". |
| 13 | + * - The 2nd place athlete's rank is "Silver Medal". |
| 14 | + * - The 3rd place athlete's rank is "Bronze Medal". |
| 15 | + * - For the 4th place to the nth place athlete, their rank is their placement number |
| 16 | + * (i.e., the xth place athlete's rank is "x"). |
| 17 | + * |
| 18 | + * Return an array answer of size n where answer[i] is the rank of the ith athlete. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} score |
| 23 | + * @return {string[]} |
| 24 | + */ |
| 25 | +var findRelativeRanks = function(score) { |
| 26 | + const PLACEMENTS = ['Gold Medal', 'Silver Medal', 'Bronze Medal']; |
| 27 | + const map = new Map(); |
| 28 | + score.forEach((rank, index) => map.set(rank, index)); |
| 29 | + |
| 30 | + const result = score.slice(); |
| 31 | + const sorted = [...map].sort(([a], [b]) => b - a); |
| 32 | + |
| 33 | + sorted.forEach(([_, index], rank) => { |
| 34 | + result[index] = PLACEMENTS[rank] || `${rank + 1}`; |
| 35 | + }); |
| 36 | + |
| 37 | + return result; |
| 38 | +}; |
0 commit comments