본문 바로가기
정리/알고리즘

해시 - 베스트앨범

by Hudini30 2022. 2. 4.

프로그래머스(해시) - 베스트앨범

해당 문제는 hashMap 2개와 정렬을 통해 문제 그대로 풀었습니다. genre 명을 key로 하나의 해시맵(이후 playListMap)은 고유 id 값을 가진 play count에 따라 정렬된 리스트를 값으로 가지고, 다른 하나(이후 totalCountMap)는 genre 명을 key로 total play count를 가지고 있습니다.

이 후 로직은 totalCountMap에서 각각의 totalCount로 정렬을 한 키값을 구한 후 그 키값 순으로 playListMap에서 데이터를 꺼내 2개 혹은 1개의 리스트를 답변 리스트에 넣은 후 그 리스트를 array로 변경하였습니다.

public int[] solution(String[] genres, int[] plays) {
        List<Integer> answerList = new ArrayList<>();
        Map<String, List<Integer>> genrePlayListMap = new HashMap<>();

        int songLength = genres.length;
        Map<String, Integer> genrePlayTotalCountMap = new HashMap<>();
        //
        for (int i = 0; i < songLength; i++) {
            String genre = genres[i];
            int playCount = plays[i];

            List<Integer> songPlayList = genrePlayListMap.getOrDefault(genre, new ArrayList<>());
            songPlayList.add(i);
            songPlayList.sort((songId1, songId2) -> plays[songId1] > plays[songId2] ? -1 : 0);
            genrePlayListMap.put(genre, songPlayList);

            int songPlayTotalCount = genrePlayTotalCountMap.getOrDefault(genre, 0);
            genrePlayTotalCountMap.put(genre, playCount + songPlayTotalCount);
        }

        genrePlayTotalCountMap.keySet().stream()
                .sorted((genre1, genre2) -> genrePlayTotalCountMap.get(genre1) > genrePlayTotalCountMap.get(genre2) ? -1 : 0)
                .collect(Collectors.toList())
                .forEach(genreName -> {
                    List<Integer> songPlayList = genrePlayListMap.get(genreName);

                    int fromIndex = Math.min(songPlayList.size(), 2);
                    answerList.addAll(songPlayList.subList(0, fromIndex));
                });

        return answerList.stream().mapToInt(value -> value).toArray();
    }

'정리 > 알고리즘' 카테고리의 다른 글

스택/큐 - 주식가격  (0) 2022.02.08
스택/큐 - 다리를 지나는 트럭  (0) 2022.02.07
스택/큐 - 프린터  (0) 2022.02.03
스택/큐 - 기능개발  (0) 2022.02.03
해시 - 위장  (0) 2022.02.03

댓글