[Pogrammers] 베스트 앨범

APRIL 02, 2021

#. 테스트 문제


#. 결과 및 풀이

1. 결과

정확성  테스트
테스트 1 〉	통과 (11.76ms, 53.1MB)
테스트 2 〉	통과 (7.69ms, 54.2MB)
테스트 3 〉	통과 (8.51ms, 53.4MB)
테스트 4 〉	통과 (7.67ms, 52.7MB)
테스트 5 〉	통과 (14.03ms, 53.1MB)
테스트 6 〉	통과 (10.96ms, 53.1MB)
테스트 7 〉	통과 (9.58ms, 53.4MB)
테스트 8 〉	통과 (13.25ms, 52.9MB)
테스트 9 〉	통과 (7.90ms, 52.6MB)
테스트 10 〉	통과 (12.32ms, 53MB)
테스트 11 〉	통과 (11.69ms, 53.1MB)
테스트 12 〉	통과 (13.67ms, 52.7MB)
테스트 13 〉	통과 (11.74ms, 53.3MB)
테스트 14 〉	통과 (14.23ms, 53.1MB)
테스트 15 〉	통과 (7.91ms, 52.4MB)

2. 풀이

@Test
void 베스트앨범() {
    Assertions.assertArrayEquals(new int[]{4, 1, 3, 0}, solution(new String[]{"classic", "pop", "classic", "classic", "pop"}, new int[]{500, 600, 150, 800, 2500}));
    Assertions.assertArrayEquals(new int[]{4, 3}, solution(new String[]{"classic", "classic", "classic", "classic", "classic"}, new int[]{500, 600, 150, 800, 2500}));
    Assertions.assertArrayEquals(new int[]{3, 4, 1, 0, 2}, solution(new String[]{"classic", "pop", "pop2", "pop4", "pop4"}, new int[]{500, 600, 150, 2500, 2500}));
}

int[] 베스트앨범_solution(String[] genres, int[] plays) {
    Map<String, GS> gs = new HashMap<>();
    
    for(int i=0; i<genres.length; i++) {
        String genre = genres[i];
        int play = plays[i];
    
        GS genreSong = gs.getOrDefault(genre, new GS());
        genreSong.total += play;
        genreSong.maxSongs.put(i, play);
        genreSong.maxSongs = genreSong.maxSongs.entrySet().stream()
            .sorted((song1, song2) -> {
                int m = song2.getValue() - song1.getValue();
                if(m == 0)
                    return song1.getKey() - song2.getKey();
                return m;
            })
            .limit(2)
            .collect(Collectors.toMap(
                e -> e.getKey(),
                e -> e.getValue(),
                (x,y) -> y,
                LinkedHashMap::new
            ));
 
        gs.put(genre, genreSong);
    }

    List<Integer> list = new ArrayList<>();
    gs.entrySet().stream()
        .sorted((g1, g2) -> g2.getValue().total - g1.getValue().total)
        .forEach(g -> {
            Map<Integer, Integer> maxSongs = g.getValue().maxSongs;

            for (Map.Entry<Integer, Integer> entry : maxSongs.entrySet()) {
                list.add(entry.getKey());
            }
    });

    return list.stream().mapToInt(i->i).toArray();
}

class GS {
    int total = 0;
    Map<Integer, Integer> maxSongs = new HashMap<>();
}

배웠다


작업 기록 블로그