[코테 스터디 9일차 TIL] Relative Ranks

dev_jubby·2024년 7월 30일
1

코테스터디

목록 보기
9/36



💛 오늘의 학습 키워드

[힙(Heap)] 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 ith rank of the ith athlete.

제한 조건

  • n == score.length
  • 1 <= n <= 104
  • 0 <= score[i] <= 106
  • All the values in score 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;
    }
}

💻 내 접근 방법

  1. 먼저 주어진 score 를 복사하기 위해서 copyOf() 를 사용한 후, sort() 메소드로 정렬을 한다.
  2. return 할 String 배열을 생성한 후, binarySearch()를 통해 찾고자 하는 값의 인덱스를 구한다.
  3. 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

profile
신입 개발자 쥬비의 기술 블로그 입니다.

0개의 댓글