Relative Ranks Problem


Description

LeetCode Problem 506.

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

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

  • The 1^st place athlete’s rank is “Gold Medal”.
  • The 2^nd place athlete’s rank is “Silver Medal”.
  • The 3^rd place athlete’s rank is “Bronze Medal”.
  • For the 4^th place to the n^th place athlete, their rank is their placement number (i.e., the x^th place athlete’s rank is “x”).

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

Example 1:

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

Example 2:

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

Constraints:

  • n == score.length
  • 1 <= n <= 10^4
  • 0 <= score[i] <= 10^6
  • All the values in score are unique.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& nums) {
        priority_queue<pair<int,int> > pq;
        for(int i=0;i<nums.size();i++) {
            pq.push(make_pair(nums[i],i));
        }
        vector<string> res(nums.size(),"");
        int count = 1;
        for(int i=0; i<nums.size();i++) {
            if(count==1) {res[pq.top().second] = "Gold Medal"; count++;}
            else if(count==2) {res[pq.top().second] = "Silver Medal"; count++;}
            else if(count==3) {res[pq.top().second] = "Bronze Medal"; count++;}
            else {res[pq.top().second] = to_string(count); count++;}
            pq.pop();
        }
        return res;
    }
};




Related Posts

Shortest Subarray With Sum At Least K Problem

LeetCode 862. Given an integer array nums and an integer...

Reachable Nodes In Subdivided Graph Problem

LeetCode 882. You are given an undirected graph (the “original...

Minimum Number Of Refueling Stops Problem

LeetCode 871. A car travels from a starting position to...

Minimum Cost To Hire K Workers Problem

LeetCode 857. There are n workers. You are given two...

K Closest Points To Origin Problem

LeetCode 973. Given an array of points where points[i] =...

Swim In Rising Water Problem

LeetCode 778. You are given an n x n integer...