506. Relative Ranks
原创
©著作权归作者所有:来自51CTO博客作者wx62ea2466cca9a的原创作品,请联系作者获取转载授权,否则将追究法律责任
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
Note:
N is a positive integer and won’t exceed 10,000.
All the scores of athletes are guaranteed to be unique.
思路:
1、用Map存储原数组中每个数的下标。
2、对原数组进行排序。
3、从后往前依次判断,前三位依次授予”Gold Medal”, “Silver Medal”, “Bronze Medal”,后面的依次授予”4”,”5”,”6”,…
class Solution {
public String[] findRelativeRanks(int[] nums) {
int len = nums.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < len; i++)
map.put(nums[i], i);
String[] result = new String[len];
String[] res = new String[]{"Gold Medal", "Silver Medal", "Bronze Medal"};
Arrays.sort(nums);
for (int i = len - 1; i >= 0; i--) {
if (i >= len - 3 && i <= len - 1)
result[map.get(nums[i])] = res[len - i - 1];
else
result[map.get(nums[i])] = "" + (len