506 Relative Ranks
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.vector<string> findRelativeRanks(vector<int>& nums) {
unordered_map<int, int> i_lookup;
i_lookup.reserve(nums.size());
for (int i = 0; i < nums.size(); i++) {
i_lookup.insert({nums[i], i});
}
sort(nums.begin(), nums.end(), greater<int>());
vector<string> ranks(nums.size(), "");
vector<string> top_ranks = {"Gold Medal", "Silver Medal", "Bronze Medal"};
for (int i = 0; i < min(3, int(nums.size())); i++) {
ranks[i_lookup[nums[i]]] = top_ranks[i];
}
int remainder = 4;
for (int i = 3; i < nums.size(); i++) {
ranks[i_lookup[nums[i]]] = to_string(remainder++);
}
return ranks;
}Last updated