506 Relative Ranks

Given the results of N athletes, find their relative positions and award the top three medals. The top three athletes will be awarded "Gold Medal", "Silver Medal", "Bronze Medal" respectively.
(Note: The higher the score, the higher the ranking.)
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", " 4", "5"]
Explanation: The top three athletes are the top three, so they will be awarded "Gold Medal", "Silver Medal" and "Gold Medal", "Silver Medal" and "Bronze Medal" respectively Bronze Medal").
The remaining two athletes, we only need to calculate their relative rankings through their results.
Hint:
    N is a positive integer and will not exceed 10000.
    All athletes have different results.
See: https://leetcode.com/problems/relative-ranks/description/

C++:

class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& nums)
    {
        int n = nums.size(), cnt = 1;
        vector<string> res(n, "");
        map<int, int> m;
        for (int i = 0; i < n; ++i)
        {
            m[nums[i]] = i;
        }
        for (auto it = m.rbegin(); it != m.rend(); ++it)
        {
            if (cnt == 1)
            {
                res[it->second] = "Gold Medal";
            }
            else if (cnt == 2)
            {
                res[it->second] = "Silver Medal";
            }
            else if (cnt == 3)
            {
                res[it->second] = "Bronze Medal";
            }
            else
            {
                res[it->second] = to_string(cnt);
            }
            ++cnt;
        }
        return res;
    }
};

 Reference: http://www.cnblogs.com/grandyang/p/6476983.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647324&siteId=291194637