프로그래머스 [JAVA] :: 등수 매기기

smi·2023년 1월 24일
0

📚 문제 정의

영어 점수와 수학 점수의 평균 점수를 기준으로 학생들의 등수를 매기려고 합니다. 영어 점수와 수학 점수를 담은 2차원 정수 배열 score가 주어질 때, 영어 점수와 수학 점수의 평균을 기준으로 매긴 등수를 담은 배열을 return하도록 solution 함수를 완성해주세요.


📝 제한사항

  • 0 ≤ score[0], score[1] ≤ 100
  • 1 ≤ score의 길이 ≤ 10
  • score의 원소 길이는 2입니다.
  • score는 중복된 원소를 갖지 않습니다.

📝 입출력 예

scoreresult
[[80, 70], [90, 50], [40, 70], [50, 80]][1, 2, 4, 3]
[[80, 70], [70, 80], [30, 50], [90, 100], [100, 90], [100, 100], [10, 30]][4, 4, 6, 2, 2, 1, 7]

💡 코드

class Solution {
    public int[] solution(int[][] score) {
        float[] average = new float[score.length];
        for(int i = 0; i < score.length; i++) {
            average[i] = (float)((score[i][0] + score[i][1]) / 2.0);
        }
        
        int[] answer = new int[score.length];
        for(int j = 0; j < score.length; j++) {
            int order = 1;
            for(int k = 0; k < score.length; k++) {
                if(average[j] < average[k]) order++;
                answer[j] = order;
            }
        }
        
        return answer;
    }
}

*주의.. float 형인 average 배열에 값을 넣을 때 / 2.0이 아닌 / 2를 하면 소수점이 나오지 않음

💡 베스트코드

import java.util.*;
class Solution {
    public int[] solution(int[][] score) {
        List<Integer> scoreList = new ArrayList<>();
        for(int[] t : score){
            scoreList.add(t[0] + t[1]);
        }
        scoreList.sort(Comparator.reverseOrder());

        int[] answer = new int[score.length];
        for(int i=0; i<score.length; i++){
            answer[i] = scoreList.indexOf(score[i][0] + score[i][1])+1;
        }
        return answer;
    }
}

memo.

❗️.indexOf() : 특정 문자나 문자열이 앞에서부터 처음 발견되는 인덱스를 반환

profile
공부한 거 올려요 :)

0개의 댓글