题目描述:
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:
- N is a positive integer and won't exceed 10,000.
- All the scores of athletes are guaranteed to be unique.
给定一个数组,给前三大的数排名是金牌、银牌和铜牌,其他数的排名就是数字。由于不是有序数组,所以先要排序,但是这样打乱了元素顺序,因此还要用哈希表存储元素和对应的下标。
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
unordered_map<int,int> hash;
int n=nums.size();
for(int i=0;i<n;i++) hash[nums[i]]=i;
sort(nums.begin(),nums.end());
vector<string> result(n,"");
for(int i=0;i<n;i++)
{
if(i==n-1) result[hash[nums[i]]]="Gold Medal";
else if(i==n-2) result[hash[nums[i]]]="Silver Medal";
else if(i==n-3) result[hash[nums[i]]]="Bronze Medal";
else result[hash[nums[i]]]=to_string(n-i);
}
return result;
}
};