Iyoungman Back-end Developer

Programmers. 베스트앨범


Problem

https://programmers.co.kr/learn/courses/30/lessons/42579


Think

  • Map과 정렬을 이용하면 해결할 수 있다.

  • 직접 해결한 문제.


Solved Code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Solution {
    public int[] solution(String[] genres, int[] plays) {
        Map<String, Integer> countMap = new HashMap<>();
        Map<String, ArrayList<Song>> songListMap = new HashMap<>();

        int length = genres.length;
        for (int i = 0; i < length; i++) {
            String genre = genres[i];
            int count = countMap.getOrDefault(genre, 0);
            countMap.put(genre, count + plays[i]);

            ArrayList<Song> songList = songListMap.getOrDefault(genre, new ArrayList<>());
            songList.add(new Song(plays[i], i));
            songListMap.put(genre, songList);
        }

        List<String> sortKeys = sortByValue(countMap);
        List<Integer> resultList = new ArrayList<>();
        for (String key : sortKeys) {
            List<Song> songList = songListMap.get(key);
            songList.sort((o1, o2) -> {
                if (o1.play == o2.play) {
                    return Integer.compare(o1.index, o2.index);
                }
                return Integer.compare(o2.play, o1.play);
            });

            resultList.add(songList.get(0).index);
            if (songList.size() > 1) {
                resultList.add(songList.get(1).index);
            }
        }

        return toArray(resultList);
    }

    private static List<String> sortByValue(Map<String, Integer> map) {
        List<String> list = new ArrayList<String>(map.keySet());
        list.sort(Comparator.comparing(map::get, Comparator.reverseOrder()));

        return list;
    }

    private static int[] toArray(List<Integer> intList) {
        return intList.stream()
                .mapToInt(i -> i)
                .toArray();
    }
}

class Song {

    int play;
    int index;

    public Song(int play, int index) {
        this.play = play;
        this.index = index;
    }
}

Comments

Content