본문 바로가기
Beakjoon&프로그래머스/Java

[프로그래머스/Java] 베스트앨범

by 현장 2026. 1. 15.

-Code

import java.util.*;

class Solution {
    static class Song {
        int index, score;
        
        public Song (int index, int score)  {
            this.index = index;
            this.score = score;
        }
    }
    
    public int[] solution(String[] genres, int[] plays) {
        int length = genres.length;
        Map<String, Integer> genreTotalScore = new HashMap<>();
        Map<String, ArrayList<Song>> genrePlayInfo = new  HashMap<>();
        for (int i = 0; i < length; i++) {
            // 전체 점수를 장르에 따라 총합을 저장
            String genre = genres[i];
            int score = genreTotalScore.getOrDefault(genre, 0) + plays[i];
            genreTotalScore.put(genre, score);
            // 장르에 따라 재생 횟수들을 index와 저장
            ArrayList<Song> playInfo = genrePlayInfo.getOrDefault(genre, new ArrayList<Song>());
            playInfo.add(new Song(i, plays[i]));
            genrePlayInfo.put(genre, playInfo);
        }
        // 정렬을 위한 리스트 정의
        ArrayList<String> sortGenres = new ArrayList<String>(genreTotalScore.keySet());
        // 종합 점수를 기준으로 내림차순 정렬
        sortGenres.sort((o1, o2) -> {
            return genreTotalScore.get(o2) - genreTotalScore.get(o1);
        });
        int idx = 0;
        ArrayList<Integer> answer = new ArrayList<>();;
        for (String genre : sortGenres) {
            ArrayList<Song> songs = genrePlayInfo.get(genre);
            // 재생 횟수의 크기 내림차순 정렬
            songs.sort((o1, o2) -> {
                if (o2.score == o1.score) {
                    return o1.index - o2.index;
                }
                return o2.score - o1.score;
            });
            // 점수가 큰 2개 혹은 그 이하만 저장
            int loopCnt = Math.min(songs.size(), 2);
            for(int i = 0; i < loopCnt; i++) {
                answer.add(songs.get(i).index);
            }
        }
        return answer.stream().mapToInt(i -> i).toArray();
    }
}

처음에 1개의 map에 다 담으려고 생각하다가 로직 구상이 꼬여서 못 짰었습니다. 2개의 map을 이용해 보라는 힌트를 얻고 그를 통해서 로직을 짜서 어느 정도 완성을 시켰지만 songs를 정렬시킬 때 index도 같이 정렬을 안 시키거나 해당 장르의 노래 정보 개수가 2보다 작은 경우를 고려 안 해서 몇 번 틀렸습니다.