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".

Example 1:

Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". 
For the left two athletes, you just need to output their relative ranks according to their scores.

Note:

  1. N is a positive integer and won't exceed 10,000.
  2. All the scores of athletes are guaranteed to be unique.

相对排名。题意很简单,给一个数组表示一堆运动员的名次,请输出他们的相对排名,前三名输出的是奖牌,之后所有人需要根据他们的分数高低给出一个相对排名。

但是这个题给????也是多于????,原因在于input里面会出现非常大的数字,出现的数字并不是数组的index。比如这个

[LeetCode] 506. Relative Ranks_leetcode

思路是桶排序。首先找到input中最大的元素,这个最大的元素是最大的score分数,这样才能知道桶排序里面到底需要多少个桶。创建了桶之后,可以从右往左扫描桶,也就是从高分往低分扫,如果找到某个index,他在原数组的相同index里面是有数字的,则给他assign medal或者数字。注意前三个人分配到奖牌之后,从第四高的分数开始,我们是分配一个相对的名次。

JavaScript实现,只是单纯的用到排序

时间O(nlogn)

空间O(n)

 1 /**
 2  * @param {number[]} nums
 3  * @return {string[]}
 4  */
 5 var findRelativeRanks = function(nums) {
 6     let sortArray = nums.slice();
 7     sortArray.sort((a, b) => b - a);
 8     let res = [];
 9     for (let i = 0; i < nums.length; i++) {
10         const j = sortArray.indexOf(nums[i]);
11         if (j === 0) {
12             res.push('Gold Medal');
13         } else if (j === 1) {
14             res.push('Silver Medal');
15         } else if (j === 2) {
16             res.push('Bronze Medal');
17         } else {
18             res.push((j + 1).toString());
19         }
20     }
21     return res;
22 };

 

Java实现 - 桶排序

时间O(n)

空间O(n)

 1 class Solution {
 2     public String[] findRelativeRanks(int[] nums) {
 3         String[] result = new String[nums.length];
 4         int max = 0;
 5         for (int i : nums) {
 6             if (i > max)
 7                 max = i;
 8         }
 9         int[] hash = new int[max + 1];
10         for (int i = 0; i < nums.length; i++) {
11             hash[nums[i]] = i + 1;
12         }
13         int place = 1;
14         for (int i = hash.length - 1; i >= 0; i--) {
15             if (hash[i] != 0) {
16                 if (place == 1) {
17                     result[hash[i] - 1] = "Gold Medal";
18                 } else if (place == 2) {
19                     result[hash[i] - 1] = "Silver Medal";
20                 } else if (place == 3) {
21                     result[hash[i] - 1] = "Bronze Medal";
22                 } else {
23                     result[hash[i] - 1] = String.valueOf(place);
24                 }
25                 place++;
26             }
27         }
28         return result;
29     }
30 }

 

LeetCode 题目总结