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

Marin·2024년 7월 30일
0

TIL

목록 보기
8/17
post-thumbnail

1 | 오늘의 문제

1. 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 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.

2. 초기 풀이

import java.util.*;

class Solution {
    public String[] findRelativeRanks(int[] score) {
        int[] array = score.clone();
        Integer[] newScore = Arrays.stream(score).boxed().toArray(Integer[]::new);
        Arrays.sort(newScore, Collections.reverseOrder()); 
        //내림차순 정렬, index 0 -> 1등

        String[] medal = new String[score.length];

        for(int i = 0; i < score.length; i++) {
            switch(i) {
                case 0 :
                    medal[i] = "Gold Medal";
                    break;
                case 1 : 
                    medal[i] = "Silver Medal";
                    break;
                case 2 : 
                    medal[i] = "Bronze Medal";
                    break;
                default :
                    medal[i] = Integer.toString(i + 1);
            } 
        }

        String[] answer = new String[score.length];
        
        for(int i = 0; i < score.length; i++) {
            for(int j = 0; j < score.length; j++) {
                if(array[i] == newScore[j]) {
                    answer[i] = medal[j];
                }
            }

            
        }

        return answer;

    }
}

내가 풀었어도 줄여야 할 점들이 너무 보인다...
배열을 너무 많이 썼고 이중 for문은 시간이 제곱으로 드니 이를 개선해야 할 것 같다.

3. 개선해야 할 점

  1. 이중 for문 제거 -> 2차원 배열로 점수와 인덱스(등수 매기기)를 같이 저장, 인
  2. 불필요한 배열 제거 -> 바로 순위 매기기로 돌입

알고리즘
1. 점수와 인덱스 쌍을 저장
2. 점수에 따라 내림차순 정렬
3. 순위 결정

사용: 내림차순 람다식 정렬
2차원 배열의 첫번째 요소를 기준으로 내림차순 정렬하기
Arrays.sort(정렬한 array, (a, b) -> b[0] - a[0])

4. 개선된 코드

import java.util.Arrays;

class Solution {
    public String[] findRelativeRanks(int[] score) {
        int n = score.length;
        String[] result = new String[n];
        
        // 점수와 인덱스를 함께 저장하는 배열 생성
        int[][] scoreWithIndex = new int[n][2];
        for (int i = 0; i < n; i++) {
            scoreWithIndex[i][0] = score[i];
            scoreWithIndex[i][1] = i;
        }
        
        // 점수에 따라 내림차순 정렬
        Arrays.sort(scoreWithIndex, (a, b) -> b[0] - a[0]);
        
        // 순위 매기기
        for (int i = 0; i < n; i++) {
            int index = scoreWithIndex[i][1];
            if (i == 0) {
                result[index] = "Gold Medal";
            } else if (i == 1) {
                result[index] = "Silver Medal";
            } else if (i == 2) {
                result[index] = "Bronze Medal";
            } else {
                result[index] = String.valueOf(i + 1);
            }
        }
        
        return result;
    }
}

5. 오늘의 키워드

  1. 람다식
    자바는 객체만을 전달할 수 있다. 필요한 것이 함수(기능)만이더라도, 객체를 생성하여 함수를 정의해야 한다. 이런 번거러움을 해결한 것이 람다식.
profile
대학생 | BE | 취준 | Fight or Flight

0개의 댓글