Simple&Natural
Hash - 베스트 앨범 본문
728x90
import java.util.*;
class Solution {
public int[] solution(String[] genres, int[] plays) {
int[] answer = {};
ArrayList<Integer> answerList = new ArrayList<>();
HashMap<String, GenreInfo> genreInfoByName = new HashMap<>();
for (int i=0; i<genres.length; i++) {
// 장르별 정보
genreInfoByName.putIfAbsent(genres[i], new GenreInfo(genres[i]));
genreInfoByName.get(genres[i]).addMusic(new Music(i, genres[i], plays[i]));
}
ArrayList<GenreInfo> genreInfoList = new ArrayList<>(genreInfoByName.values());
Collections.sort(genreInfoList);
for (GenreInfo genreInfo : genreInfoList) {
genreInfo.sortMusic();
answerList.add(genreInfo.getMusic(0).id);
if (genreInfo.getCount() > 1) {
answerList.add(genreInfo.getMusic(1).id);
}
}
int[] answerArray = new int[answerList.size()];
int index = 0;
for (int id : answerList) {
answerArray[index++] = id;
}
answer = answerArray;
return answer;
}
}
class Music implements Comparable {
int id;
String genre;
int play;
Music(int id, String genre, int play) {
this.id = id;
this.genre = genre;
this.play = play;
}
public int getId() {
return this.id;
}
public String getGenre() {
return this.genre;
}
public int getPlay() {
return this.play;
}
@Override
public int compareTo(Object object) {
Music otherMusic = (Music) object;
if (otherMusic.play == this.play) {
return this.id - otherMusic.id;
}
return otherMusic.play - this.play; // 내림차순
}
}
class GenreInfo implements Comparable {
final String genre;
private final ArrayList<Music> musics = new ArrayList<>();
GenreInfo(String genre) {
this.genre = genre;
}
public void addMusic(Music music) {
this.musics.add(music);
}
public int getCount() {
return this.musics.size();
}
public int totalPlays() {
int count = 0;
for (Music music : musics) {
count += music.play;
}
return count;
}
public void sortMusic() {
Collections.sort(musics);
}
public ArrayList<Music> getMusics() {
return this.musics;
}
public Music getMusic(int index) {
return this.musics.get(index);
}
@Override
public int compareTo(Object otherInfo) {
return ((GenreInfo) otherInfo).totalPlays() - this.totalPlays();
}
}
728x90
'코딩테스트 풀이 > 프로그래머스' 카테고리의 다른 글
정렬 - 가장 큰 수 (0) | 2022.04.30 |
---|---|
Hash - 전화번호 목록 (0) | 2022.04.24 |
Hash - 완주하지 못한 선수 (0) | 2022.04.23 |
2021 dev-matching - 로또의 최고 순위와 최저 순위 (0) | 2021.08.13 |
프로그래머스 Winter/Summer Coding 종이접기 문제 (0) | 2020.05.29 |