[코테 풀이] Relative Ranks

시내·2024년 7월 26일
0

Q_506) Relative Ranks

출처 : https://leetcode.com/problems/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 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.

class Solution {
    public class ScoreWithIndex {
        int score;
        int index;

        ScoreWithIndex(int score, int index) {
            this.score = score;
            this.index = index;
        }
    }

    public class inOrder implements Comparator<ScoreWithIndex> {

        @Override
        public int compare(ScoreWithIndex o1, ScoreWithIndex o2) {
            return o2.score - o1.score; //descending
        }
    }
    
    public String[] findRelativeRanks(int[] score) {
        int[] sub = new int[score.length];
        String[] answer = new String[score.length];
        ArrayList<ScoreWithIndex> arrayList = new ArrayList<>();
        for (int i = 0; i < score.length; i++) {
            arrayList.add(new ScoreWithIndex(score[i], i));
        }
        Collections.sort(arrayList, new inOrder());
        int ind = 0;
        for (int q = 0; q < arrayList.size(); q++) {
            sub[arrayList.get(q).index] = ind++;
        }
        for (int p = 0; p < answer.length; p++) {
            if (sub[p] == 0) answer[p] = "Gold Medal";
            else if (sub[p] == 1) answer[p] = "Silver Medal";
            else if (sub[p] == 2) answer[p] = "Bronze Medal";
            else answer[p] = Integer.toString(sub[p] + 1);
        }
        return answer;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글