Leetcode506. Relative Ranks简单粗暴

本文介绍了一种算法,该算法能够根据运动员的成绩找出他们的相对排名,并为前三名分配金牌、银牌和铜牌。通过使用C++实现,文章详细展示了如何利用排序和哈希映射来高效地解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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".

class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& nums) {
        vector<int> vi(nums.begin(), nums.end());
        vector<string> vs;
        std::sort(nums.begin(), nums.end(), [](int a, int b){
           return a > b; 
        });
        unordered_map<int, int> map;
        for (int i = 0; i < nums.size(); i++){
            map[nums[i]] = i;
        }
        for (int a : vi)
        {
            if (map[a] == 0) {
                vs.push_back("Gold Medal");
            } else if (map[a] == 1) {
                vs.push_back("Silver Medal");
            } else if (map[a] == 2) {
                vs.push_back("Bronze Medal");
            } else {
                vs.push_back(std::to_string(map[a] + 1));
            }
        }
        return vs;
    }
};