
-Code
import java.util.*;
class Solution {
static class Song {
int index, score;
public Song (int index, int score) {
this.index = index;
this.score = score;
}
}
public int[] solution(String[] genres, int[] plays) {
int length = genres.length;
Map<String, Integer> genreTotalScore = new HashMap<>();
Map<String, ArrayList<Song>> genrePlayInfo = new HashMap<>();
for (int i = 0; i < length; i++) {
// 전체 점수를 장르에 따라 총합을 저장
String genre = genres[i];
int score = genreTotalScore.getOrDefault(genre, 0) + plays[i];
genreTotalScore.put(genre, score);
// 장르에 따라 재생 횟수들을 index와 저장
ArrayList<Song> playInfo = genrePlayInfo.getOrDefault(genre, new ArrayList<Song>());
playInfo.add(new Song(i, plays[i]));
genrePlayInfo.put(genre, playInfo);
}
// 정렬을 위한 리스트 정의
ArrayList<String> sortGenres = new ArrayList<String>(genreTotalScore.keySet());
// 종합 점수를 기준으로 내림차순 정렬
sortGenres.sort((o1, o2) -> {
return genreTotalScore.get(o2) - genreTotalScore.get(o1);
});
int idx = 0;
ArrayList<Integer> answer = new ArrayList<>();;
for (String genre : sortGenres) {
ArrayList<Song> songs = genrePlayInfo.get(genre);
// 재생 횟수의 크기 내림차순 정렬
songs.sort((o1, o2) -> {
if (o2.score == o1.score) {
return o1.index - o2.index;
}
return o2.score - o1.score;
});
// 점수가 큰 2개 혹은 그 이하만 저장
int loopCnt = Math.min(songs.size(), 2);
for(int i = 0; i < loopCnt; i++) {
answer.add(songs.get(i).index);
}
}
return answer.stream().mapToInt(i -> i).toArray();
}
}
처음에 1개의 map에 다 담으려고 생각하다가 로직 구상이 꼬여서 못 짰었습니다. 2개의 map을 이용해 보라는 힌트를 얻고 그를 통해서 로직을 짜서 어느 정도 완성을 시켰지만 songs를 정렬시킬 때 index도 같이 정렬을 안 시키거나 해당 장르의 노래 정보 개수가 2보다 작은 경우를 고려 안 해서 몇 번 틀렸습니다.
'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [백준/Java] 2156번 포도주 시식 (0) | 2026.01.16 |
|---|---|
| [백준/Java] 2579번 계단 오르기 (0) | 2026.01.16 |
| [백준/Java] 32952번 비트코인 반감기 (0) | 2026.01.15 |
| [백준/Java] 11054번 가장 긴 바이토닉 부분 수열 (0) | 2026.01.14 |
| [백준/Java] 10844번 쉬운 계단 수 (0) | 2026.01.14 |