배꼽파지 않도록 잘 개발해요

99클럽 코테 스터디 9일차 TIL - Relative Ranks 본문

코딩테스트/99클럽

99클럽 코테 스터디 9일차 TIL - Relative Ranks

꼽파 2024. 7. 31. 09:02


Relative Ranks

출처 : Leet Code

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.

Example 1:
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].

 

Example 2:
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].

Constraints:
n == score.length
1 <= n <= 104
0 <= score[i] <= 106
All the values in score are unique.


풀이

자바스크립트

var findRelativeRanks = function(score) {
    const answer = new Array(score.length);

    // 1. 인덱스와 점수가 함께 있는 배열 만들기
    const scoreArr = score.map((sco, idx) => [idx, sco]);
    // console.log(scoreArr) 
    // [ [ 0, 10 ], [ 1, 3 ], [ 2, 8 ], [ 3, 9 ], [ 4, 4 ] ]
    // 0: 인덱스, 1: 점수
    
    // 2. 점수 기준으로 내림차순 정렬하기
    // scoreArr의 첫 번째 인덱스를 기준으로 내림차순 정렬
    const sortedArr = scoreArr.sort((a, b) => b[1] - a[1]);
    // console.log(sortedArr)
    // [ [ 0, 10 ], [ 3, 9 ], [ 2, 8 ], [ 4, 4 ], [ 1, 3 ] ]

    // 3. 순위 부여
    for (let i = 0; i < sortedArr.length; i++) {
        let [idx, score] = sortedArr[i];
        if (i === 0) answer[idx] = "Gold Medal"
        else if (i === 1) answer[idx] = "Silver Medal"
        else if (i === 2) answer[idx] = "Bronze Medal"
        else answer[idx] = (i + 1).toString();
    }
    return answer;
};

 

풀이 과정

  1. [점수, 인덱스]를 저장하고 있는 새 배열(scoreArr)을 만든다.
    이유 : 주어진 초기 배열에서의 인덱스값을 알아야 순위를 계산한 후에 매핑이 가능하다.
  2. 새 배열을 점수 기준으로 내림차순 정렬을 한다.
    이유 : 높은 점수부터 정렬을 해야 인덱스 값을 활용하여 메달 순위를 매길 수 있다.
  3. for 반복문으로 인덱스 값에 맞게 순위를 부여한다.
    이유 : 인덱스(i)값이 곧 순위이므로 조건문으로 순위를 매긴다.

시행착오

문제

  • 순위부여를 할 때 let [idx, score] = sortedArr[i];는 점수대로 정렬된 배열의 인덱스값인 i값에 따라 answer 배열에 기존 배열의 인덱스인 idx 위치에 새로운 순위를 넣어주기 위함이다.
  • 그러므로 점수순으로 정렬된 배열의 인덱스인 i와 기존 배열의 인덱스인 idx를 헷갈리면 안 된다. 이것을 헷갈려서 몇 번 실패를 하였다.

해결

  • 해결방안으로는 두 번째 케이스의 예시를 console.log로 출력하여 주석으로 작성하였다.
  • 보통 첫 번째 테스트 케이스는 단순한 경우가 많아 두 번째 테스트 케이스를 활용하여 더 명확한 비교 분석이 가능할 확률이 높다.

 

힙 구현하는 건 이따 쓰도록 하겠다.

파이썬은 라이브러리를 쓰면 되는 자바스크립트는 직접 구현해야하는 점이 참 버겁다.

728x90