506. Relative Ranks[Easy]
Description
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.
Solution
一开始没理解题目,直接一个排序然后按顺序名次123,发现WA。然后看测例,发现是按照输入顺序对应输出相应的名次。C++可以直接用优先队列排序,用一对数存对应的分数和出现的位置,即make_pair(nums[i],i)
每次取优先队列的第一个,赋值当前名次,加入返回的vector即可。
Complexity analysis
O(n)
Code
class Solution {
public:
string trans(int x) {
ostringstream stream;
stream<<x;
return stream.str();
}
vector<string> findRelativeRanks(vector<int>& nums) {
priority_queue<pair<int, int>> que;
for (int i = 0; i < nums.size(); i++) {
que.push(make_pair(nums[i],i));
}
vector<string> result(nums.size(), ""); //记得初始化
int count = 1;
for (int i = 0; i < nums.size(); i++) {
if (count == 1) {
result[que.top().second] = "Gold Medal";
count++;
} else if (count == 2) {
result[que.top().second] = "Silver Medal";
count++;
} else if (count == 3) {
result[que.top().second] = "Bronze Medal";
count++;
} else {
result[que.top().second] = trans(count);
count++;
}
que.pop();
}
return result;
}
};