베스트앨범


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

문제보기
Alt text

소스코드

import java.util.*;


class Solution {
     public static List<Integer> solution(String[] genres, int[] plays) {

        Map<String, Song> songMap = new HashMap<>();

        for (int i = 0; i < genres.length; i++) {
            String genre = genres[i];
            Song song;

            if (songMap.containsKey(genre)) {
                song = songMap.get(genre);
            } else {
                song = new Song();
            }

            song.totalPlay += plays[i];
            song.playList.add(new Play(i, plays[i]));
            songMap.put(genre, song);
        }

        // 각 장르별 많이 재생된 순으로 정렬
        List<Map.Entry<String, Song>> entryList = new LinkedList<>(songMap.entrySet());
        entryList.sort(new Comparator<Map.Entry<String, Song>>() {
            @Override
            public int compare(Map.Entry<String, Song> o1, Map.Entry<String, Song> o2) {
                return Long.compare(o2.getValue().totalPlay, o1.getValue().totalPlay);
            }
        });

        // 각 장르별 최대 2개의 노래 출력
        List<Integer> answer = new ArrayList<>();
        for (Map.Entry<String, Song> song : entryList) {
            List<Play> playList = song.getValue().playList;
            Collections.sort(playList);

            int bestSongCnt = 0;
            for (Play play : playList) {
                if (bestSongCnt == 2) break;

                answer.add(play.songNo);
                bestSongCnt++;
            }
        }


        return answer;
    }
}

class Song {
    long totalPlay;
    List<Play> playList = new ArrayList<>();
}

class Play implements Comparable<Play> {
    int songNo;
    int playCnt;

    public Play(int songNo, int playCnt) {
        this.songNo = songNo;
        this.playCnt = playCnt;
    }

    @Override
    public int compareTo(Play comparePlay) {
        int compareResult = Integer.compare(comparePlay.playCnt, this.playCnt);

        if (compareResult == 0) {
            compareResult = Integer.compare(this.songNo, comparePlay.songNo);
        }

        return compareResult;
    }
}