
문제 설명
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:
1st place athlete's rank is "Gold Medal".2nd place athlete's rank is "Silver Medal".3rd place athlete's rank is "Bronze Medal".4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").answer of size n where answer[i] is the ith rank of the ith athlete.제한 조건
n == score.length1 <= n <= 1040 <= score[i] <= 106score are unique.입출력 예
Example1
Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].
Example2
Input: score = [10,3,8,9,4]
Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].
import java.util.*;
class Solution {
public String[] findRelativeRanks(int[] score) {
// 배열 사이즈
int size = score.length;
// 배열 복사 및 정렬
int[] arr = Arrays.copyOf(score, size);
Arrays.sort(arr);
// return 할 객체 생성
String[] ranks = new String[size];
for (int i = 0; i < size; i++) {
// 이진탐색
int rank = size - Arrays.binarySearch(arr, score[i]);
if (rank == 1) {
ranks[i] = "Gold Medal";
} else if (rank == 2) {
ranks[i] = "Silver Medal";
} else if (rank == 3) {
ranks[i] = "Bronze Medal";
} else {
ranks[i] = String.valueOf(rank);
}
}
return ranks;
}
}
score 를 복사하기 위해서 copyOf() 를 사용한 후, sort() 메소드로 정렬을 한다.binarySearch()를 통해 찾고자 하는 값의 인덱스를 구한다.sort는 오름차순으로 되어 있기 때문에, size 에서 index 값을 뺀 rank 를 인덱스로 사용해서 값을 넣는다.
stream으로sorted()함수 사용하는 법// 오름차순 stream().sorted(); // 내림차순 stream().sorted(Comparator.reverseOrder());

처음에 한번에 배열 복사한 후 정렬까지 진행하려고, int[] arr = Arrays.stream(Arrays.copyOf(score,size)).sorted().toArray() 를 사용했는데, 오히려 효율은 떨어지는 모습이 보였다. 그리고 또 copyOf()를 사용하는 것보다 for()문을 사용해서 배열을 복사하는게 더 좋은 성능을 보였다. 간결한 코드이냐 효율이냐 하면 당연 그래도 효율이지..!
참고
https://silverbullet.tistory.com/entry/Java-Stream-sorted-정렬오름차순-정렬-내림차순-정렬
https://bbangson.tistory.com/73