Relative Ranks

You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.

The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd the highest score, and so on. The placement of each athlete determines their rank:

1.The 1st place athlete's rank is "Gold Medal".

2.The 2nd place athlete's rank is "Silver Medal".

3.The 3rd place athlete's rank is "Bronze Medal".

4.For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").

Return an array answer of size n where answer[i] is the rank of the ith athlete.

Example:

Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<stringfindRelativeRanks(vector<int&nums)
{
    vector<pair<intint>> v;
    for (int i = 0i < nums.size(); i++)
        v.push_back({nums[i]i});
    sort(v.begin(), v.end());
    vector<stringres(nums.size());
    //res.resize(nums.size());
    int l = 4;
    int n = nums.size();
    if (n == 0)
        return res;

    res[v[n - 1].second] = "Gold Medal";
    if (n == 1)
        return res;
    res[v[n - 2].second] = "Silver Medal";
    if (n == 2)
        return res;
    res[v[n - 3].second] = "Bronze Medal";
    if (n == 3)
        return res;
    for (int i = nums.size() - 4i >= 0i--)
    {
        res[v[i].second] = to_string(l++);
    }
    return res;
}

int main()
{
    vector<intscore = {54321};

    vector<stringres = findRelativeRanks(score);

    cout << "[";
    for (int i = 0i < res.size(); i++)
    {

        cout << res[i];
        if (i != res.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment