506. Relative Ranks

1. 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”.

2. Example

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.

3. Note

  • N is a positive integer and won’t exceed 10,000.
  • All the scores of athletes are guaranteed to be unique.

4. Solutions

My Accepted Solution

n = i_scores.size()
Time complexity: O($nlog_2n$)
Space complexity: O(n)

class Solution 
{
public:
    // vector<string> findRelativeRanks(vector<int>& nums)
    vector<string> findRelativeRanks(vector<int> &i_scores) 
    {
        vector<pair<int, int>> scoresWithOriginIndex(i_scores.size());
        for(int i = 0; i < i_scores.size(); i++)
        {
            scoresWithOriginIndex[i] = {i_scores[i], i};
        }
        
        sort(scoresWithOriginIndex.begin(), scoresWithOriginIndex.end(), [](pair<int, int> left, pair<int, int> right){return left.first > right.first;});
        
        vector<string> result(i_scores.size());
        map<int, string> ranks = {{1, "Gold Medal"}, {2, "Silver Medal"}, {3, "Bronze Medal"}};
        for(int i = 0; i < scoresWithOriginIndex.size(); i++)
        {
            string rank = (i >= 3 ? to_string(i+1) : ranks[i+1]);
            
            result[scoresWithOriginIndex[i].second] = rank;
        }
        
        return result;
    }
};
Last updated:
Tags:
comments powered by Disqus