Header Ad

Leetcode Relative Ranks problem solution

In this Leetcode Relative Ranks problem solution 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 highest score, and so on. The placement of each athlete determines their rank:

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

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

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

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.

Leetcode Relative Ranks problem solution

Problem solution in Python.

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        position = score[:]
        thisdict = {}
        for i,key in enumerate(position):
            thisdict[key] = str(i+1)
        result = []
        for x in score:
            value = thisdict[x]
            if value == '1':
                value = "Gold Medal"
            elif value == '2':
                value = "Silver Medal"
            elif value == '3':
                value = "Bronze Medal"
        return result

Problem solution in Java.

class Solution {
public String[] findRelativeRanks(int[] nums) {
    int[] sorted=nums.clone();
    int i=0,j=nums.length-1;
    while(i<j){int temp=sorted[i];sorted[i]=sorted[j];sorted[j]=temp;i++;j--;}
    HashMap<Integer,String> map=new HashMap();
    for(int k=0;k<nums.length;k++)map.put(sorted[k],String.valueOf(k+1));
    String[] output=new String[nums.length];
    int k=0;
    for(int a:nums){
        if(map.get(a).equals("1"))output[k]="Gold Medal";
        else if(map.get(a).equals("2"))output[k]="Silver Medal";
        else if(map.get(a).equals("3"))output[k]="Bronze Medal";
        else output[k]=map.get(a);k++;
    return output;

Problem solution in C++.

class Solution {
    vector<string> findRelativeRanks(vector<int>& nums) {
        priority_queue<pair<int,int> > pq;
        for(int i=0;i<nums.size();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++;}
        return res;

Post a Comment