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.
import java.util.*;
class Solution {
public String[] findRelativeRanks(int[] score) {
int n = score.length;
String[] result = new String[n];
int[][] scoresWithIndex = new int[n][2];
// 각 선수의 점수와 인덱스를 배열에 저장
for (int i = 0; i < n; i++) {
scoresWithIndex[i][0] = score[i];
scoresWithIndex[i][1] = i;
}
// 점수에 따라 내림차순으로 정렬
Arrays.sort(scoresWithIndex, (a, b) -> b[0] - a[0]);
// 순위 할당
for (int rank = 0; rank < n; rank++) {
int index = scoresWithIndex[rank][1];
if (rank == 0) {
result[index] = "Gold Medal";
} else if (rank == 1) {
result[index] = "Silver Medal";
} else if (rank == 2) {
result[index] = "Bronze Medal";
} else {
result[index] = Integer.toString(rank + 1);
}
}
return result;
}
}
문제의 핵심은 주어진 점수 배열에서 각 점수가 몇 번째로 높은지를 결정한다는 점! 이것만 해결하니 금방 풀 수 있었다.