[프로그래머스] 베스트 앨범
2020. 5. 8. 16:53ㆍ프로그래머스/LEVEL 3
import java.util.*;
class Solution {
class song{
int plays;
String genres;
int index;
song(int plays, String genres,int index){
this.plays=plays;
this.genres= genres;
this.index = index;
}
}
class Compare{
String genres;
int totalPlays;
Compare(String genres, int totalPlays){
this.genres = genres;
this.totalPlays = totalPlays;
}
}
public int[] solution(String[] genres, int[] plays) {
int[] answer = {};
List<Integer> answerList = new ArrayList<>();
Map<String,Integer> countGenres = new HashMap<>();
List<song> songs = new ArrayList<>();
List<Compare> compares = new ArrayList<>();
for(int i=0; i<genres.length; i++){
songs.add(new song(plays[i],genres[i],i));
}
Collections.sort(songs, new Comparator<song>(){
public int compare(song s1, song s2){
if(s1.plays==s2.plays){
return 0;
}else{
return s2.plays - s1.plays;
}
}
});
for(int i=0; i<genres.length; i++){
if(countGenres.containsKey(genres[i])){
countGenres.put(genres[i],countGenres.get(genres[i])+plays[i]);
}else{
countGenres.put(genres[i],plays[i]);
}
}
for(String s : countGenres.keySet()){
compares.add(new Compare(s,countGenres.get(s)));
}
Collections.sort(compares, new Comparator<Compare>(){
public int compare(Compare c1, Compare c2){
return c2.totalPlays - c1.totalPlays;
}
});
for(int i=0; i<compares.size(); i++){
int count=0;
for(int k=0; k<songs.size(); k++){
if(songs.get(k).genres.equals(compares.get(i).genres)){
answerList.add(songs.get(k).index);
count++;
}
if(count==2){
break;
}
}
}
answer = new int[answerList.size()];
for(int i=0; i<answer.length; i++){
answer[i] = answerList.get(i);
}
return answer;
}
}
메소드로 분리해서 푸는 습관을 들여야겠다...
'프로그래머스 > LEVEL 3' 카테고리의 다른 글
[프로그래머스] 이중 우선순위 큐 (0) | 2020.05.08 |
---|---|
[프로그래머스] 디스크 컨트롤러 (0) | 2020.05.02 |