★ [프로그래머스][JAVA] 베스트앨범 (해시맵, Comparator)

★ [프로그래머스][JAVA] 베스트앨범 (해시맵, Comparator)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

import java.util. * ; class Solution { public class Genre{ String genre; public int playTotal; List < int [] > top2; public Genre( String genre){ this .genre = genre; playTotal = 0 ; top2 = new LinkedList < > (); } public void addSong( int idx, int playTime){ playTotal + = playTime; top2. add ( new int []{idx, playTime}); Collections.sort(top2, (a,b) - > b[ 1 ] - a[ 1 ]); } public int Compare(Genre g1, Genre g2){ return - (g1.playTotal - g2.playTotal); } } public int [] solution( String [] genres, int [] plays) { Map < String , Genre > gm = new TreeMap < > (); for ( int i = 0 ; i < genres. length ; i + + ){ String genre = genres[i]; Genre currGenre = gm.getOrDefault(genre, new Genre(genre)); currGenre.addSong(i, plays[i]); gm.put(genre, currGenre); } List < Integer > res = new ArrayList < > (); List < Genre > list = new ArrayList < > (gm.values()); list.sort((g1,g2) - > g2.playTotal - g1.playTotal); for (Genre g : list){ List < int [] > top2 = g.top2; int max = 2 ; for ( int [] arr : top2){ res. add (arr[ 0 ]); if ( - - max < = 0 ) break ; } } int [] answer = new int [res.size()]; for ( int i = 0 ; i < res.size(); i + + ) answer[i] = res.get(i); return answer; } } Colored by Color Scripter

from http://aig2029.tistory.com/329 by ccl(A) rewrite - 2021-10-08 18:27:37