[LeetCode] Relative Ranks

아르당·2026년 1월 22일

LeetCode

목록 보기
106/134
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

크기가 n이고, score[i]가 대회에서 i번째 선수의 점수인 정수 배열 score가 주어진다. 모든 점수는 고유하다.

선수들은 점수에 따라 순위가 정해지는데, 1위는 가장 높은 점수를 받은 선수, 2위는 두 번째로 높은 점수를 받은 선수 등으로 결정된다. 각 선수의 순위는 그들의 랭킹을 결정한다.

  • 1위 선수의 등급은 "Gold Medal"이다.
  • 2위 선수의 등급은 "Silver Medal"이다.
  • 3위 선수의 등급은 "Bronze Medal"이다.
  • 4위부터 n위까지의 선수에게는 순위가 순위 번호와 같다(예: x위 선수의 순위는 "x"이다.)

크기가 n인 배열 answer를 반환해라. 여기서 answer[i]는 i번째 선수의 순위이다.

Example

#1
Input: score = [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: 순위는 [1st, 2nd, 3rd, 4th, 5th]이다.

#2
Input: score = [10, 3, 8, 9, 4]
Output: ["Gold Medal", "5", "Bronze Medal", "Silver Medal", "4"]
Explanation: 순위는 [1st, 5th, 3rd, 2nd, 4th]이다.

Constraints

  • n == score.length
  • 1 <= n <= 10^4
  • 0 <= score[i] <= 10^6
  • score의 모든 값들은 고유하다.

Solved

class Solution {
    public String[] findRelativeRanks(int[] score) {
        int n = score.length;
        int [][] sortedPairs = new int[n][2];

        for(int i = 0; i < n; i++) sortedPairs[i] = new int[]{i, score[i]};

        Arrays.sort(sortedPairs, (x, y) -> (y[1] - x[1]));

        String[] ans = new String[n];

        for(int i = 0; i < n; i++){
            if(i == 0) ans[sortedPairs[i][0]] = "Gold Medal";
            else if(i == 1) ans[sortedPairs[i][0]] = "Silver Medal";
            else if(i == 2) ans[sortedPairs[i][0]] = "Bronze Medal";
            else ans[sortedPairs[i][0]] = String.valueOf(i + 1);
        }

        return ans;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글