Saturday, March 7, 2020

506. Relative Ranks -E

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:
  1. N is a positive integer and won't exceed 10,000.
  2. All the scores of athletes are guaranteed to be unique.




A:

就是排序,然后再根据index输出
class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& nums) {
        unordered_map<int,int> M;
        vector<int> T=nums;
        sort(T.begin(), T.end(), greater<>());// !!!!!!!!!!!!!!!!
        for(int i =0;i<T.size();++i)
            M.insert({T[i], i+1});
        vector<string> res;
        for(auto v:nums)
        {
            auto it = M.find(v);
            if(it->second == 1)
                res.push_back("Gold Medal");
            else if(it->second == 2)
                res.push_back("Silver Medal");
            else if(it->second == 3)
                res.push_back( "Bronze Medal");
            else
                res.push_back(to_string(it->second));
        }
        return res;
    }
};


Mistakes:

1:  没有考虑到,输出的时候,需要根据nums. 原本的顺序,因此,需要对其copy 来进行sort
2:   sort时, 没有考虑到,应该降序。

No comments:

Post a Comment