문제

영어 점수와 수학 점수의 평균 점수를 기준으로 학생들의 등수를 매기려고 합니다.
영어 점수와 수학 점수를 담은 2차원 정수 배열 score가 주어질 때,
영어 점수와 수학 점수의 평균을 기준으로 매긴 등수를 담은 배열을 return하도록 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());

    System.out.println(scoreList);

    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;
}

풀이

평균을 구해야하지만 어차피 다 안나누면 순서를 나눌 수 있다.
list에 담아서 역순으로 만들었다.
그리고 list의 메소드인 indexOf을 사용햇다. indexOf는 주어진 값이 그 list에서 맨처음으로 나오는 것이 몇번째 인덱스인지 조사하는 것이다.
String의 iddexOf랑 비슷하다.
본 배열을 기준값으로 넣어서 몇번째에 등장했는지를 알면 역순으로 몇번인지 알게 된다. 중복의 경우는 첫번째값이 나오기때문에 같은 결과를 얻을 수 있다.

진료순서구하기 다시풀기

진료순서를 구했던 문제를 이것을 이용해서 더 쉽게 풀 수 있다

public static int[] solution(int[] emergency) {
        List<Integer> list = new ArrayList<>();
        for (int t : emergency) {
            list.add(t);
        }
        System.out.println(list);
        list.sort(Comparator.reverseOrder());
        System.out.println(list);
        int[] answer = new int[emergency.length];
        for (int i = 0; i < emergency.length; i++) {
            answer[i] = list.indexOf(emergency[i]) +1 ;
        }
        return answer;
    }

+ Recent posts