506. Relative Ranks (Easy)

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.

Solution: Sorting

Time complexity: $$O(NlgN)$$. Space complexity: $$O(N)$$. N is the number of scores.

Basically this question is to find out the score -> ranking mapping. The easiest way is to sort those scores in nums. But we will lose their original order. We can create (score , original index) pairs and sort them by score decreasingly. Then we will have score -> ranking (new index) mapping and we can use original index to create the result.

Example:

nums[i]    : [10, 3, 8, 9, 4]
pair[i][0] : [10, 3, 8, 9, 4]
pair[i][1] : [ 0, 1, 2, 3, 4]

After sort:
pair[i][0] : [10, 9, 8, 4, 3]
pair[i][1] : [ 0, 3, 2, 4, 1]

version 1: 12ms

class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& nums) {
        vector<pair<int,int>> rank;
        for (int i = 0; i < nums.size(); ++i) {
            rank.push_back({nums[i], i});
        }

        sort(rank.begin(), rank.end(), greater<pair<int,int>>());

        vector<string> ranks(nums.size());
        for (int i = 3; i < nums.size(); ++i) {
            ranks[rank[i].second] = to_string(i+1);
        }

        if (nums.size() > 0) ranks[rank[0].second] = "Gold Medal";
        if (nums.size() > 1) ranks[rank[1].second] = "Silver Medal";
        if (nums.size() > 2) ranks[rank[2].second] = "Bronze Medal";

        return ranks;
    }
};

version 2: 9ms

class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& nums) {
        vector<int> rank;
        for (int i = 0; i < nums.size(); ++i) rank.push_back(i);

        sort(rank.begin(), rank.end(), [&](int a, int b) { return nums[a] > nums[b];});

        vector<string> ranks(nums.size());
        for (int i = 3; i < nums.size(); ++i) {
            ranks[rank[i]] = to_string(i+1);
        }

        if (nums.size() > 0) ranks[rank[0]] = "Gold Medal";
        if (nums.size() > 1) ranks[rank[1]] = "Silver Medal";
        if (nums.size() > 2) ranks[rank[2]] = "Bronze Medal";

        return ranks;
    }
};

results matching ""

    No results matching ""