코딩테스트 연습/프로그래머스 LV.0

[프로그래머스] Lv.0 등수 매기기 - 자바(Java)

5ein 2024. 4. 22. 21:06

문제: 코딩테스트 연습 - 등수 매기기 | 프로그래머스 스쿨 (programmers.co.kr)

문제설명

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


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

입출력 예

score result
[[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]

나의 문제 풀이

import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;

class Solution {
    public int[] solution(int[][] score) {
    	List<Integer> scoreList = new ArrayList<>();
    	for (int[] i : score) {
            scoreList.add(i[0] + i[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;
    }
}

다른 사람의 문제풀이

import java.util.*;
class Solution {
    public int[] solution(int[][] score) {
        int[] answer = new int[score.length];
        float[] average = new float[score.length];
        for (int idx = 0; idx < score.length; idx++) {
            float ave = (float) (score[idx][1] + score[idx][0]) / 2f; // 평균값
            average[idx] = ave; // 평균값 배열
        }
        Arrays.sort(average); // 평균배열의 내림차순
        int rank = 0;
        int chkCount = 0;
        int[] grades = new int[average.length];
        Map<Float, Integer> averageMap = new HashMap<Float, Integer>();
        for (int idx = average.length - 1; idx >= 0; idx--) {
            float grade = average[idx];
            if (averageMap.containsKey(grade)) {
                chkCount++;
            } else {
                rank += chkCount + 1;
                chkCount = 0;
            }
            averageMap.put(grade, rank);
        }
        for (int idx = 0; idx < score.length; idx++) {
            float ave = (float) (score[idx][1] + score[idx][0]) / 2f; // 평균값
            answer[idx] = averageMap.get(ave); // 평균값 랭크
        }
        return answer;
    }
}

느낀점

float 배열을 사용한 것이 신기해서 가져와봤다!


문제 출처: 코딩테스트 연습 | 프로그래머스 스쿨 (programmers.co.kr)