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.
这题就是把一个数组,求每个元素在数组里是第几大的,最大的输出“金牌”,第二的输出“”银牌”,第三输出“铜牌”,其余的输出自己的名次。
思路是建一个堆(priority_queue),放进去的是这个数本身和他的位置组成的pair,然后依次输出,前三个就是分别是金银铜牌,输出的顺序就是要求的顺序。
代码如下:
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
priority_queue<pair<int, int> > pq;
int n = nums.size();
vector<string> res(n, "");
for(int i = 0; i < n; i++)
{
pq.push(pair<int, int>(nums[i], i));
}
for(int i = 1; i <= n; i++)
{
int pos = pq.top().second;
pq.pop();
if(i == 1)
res[pos] = "Gold Medal";
else if(i == 2)
res[pos] = "Silver Medal";
else if(i == 3)
res[pos] = "Bronze Medal";
else res[pos] = to_string(i);
}
return res;
}
};