문제 :
https://school.programmers.co.kr/learn/courses/30/lessons/42579
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
접근 :
- 가장 많이 재생된 장르 순대로 앨범을 만든다.
- 앨범은 최대 2곡까지 수록할 수 있으며 만약 1곡만 수록되어 있다면 1곡 만 포함한다.
- 앨범에서 노래의 수록 방법은 재생수가 많은 순으로 수록하며, 만약 재생수가 같다면 고유번호가 작은 순으로 선택한다.
* 문제의 조건에서 장르별 동일한 조회수는 없다고 명시
- 장르 객체를 생성하고 장르 객체안에 노래 객체 리스트를 가지고 있는다.
- 장르 객체를 HashMap 으로 { Key를 장르명 : Value를 장르 클래스} 로 지정한다.
- 노래의 재생수를 순서대로 순회하면서 장르를 체크하여 HashMap 에 저장한다.
(노래를 저장할 때에는, 해당 장르의 재생 수를 업데이트 한다.)
- 장르를 재생 순서대로 꺼내서 장르가 가지고 있는 노래를 위의 조건의 우선순위대로 꺼내서 앨범에 포함시킨 후 출력한다.
코드 구현 :
import java.util.*;
import java.util.stream.Collectors;
class Solution {
private static class Genre implements Comparable<Genre> {
private String name;
private List<Song> songs;
private int play;
public Genre(String name){
this.name = name;
songs = new ArrayList<>();
}
public boolean addSong(Song song){
this.play += song.play;
return songs.add(song);
}
@Override
public int compareTo(Genre o) {
return play - o.play;
}
}
private static class Song implements Comparable<Song>{
private int id;
private int play;
public Song(int id, int play){
this.id = id;
this.play = play;
}
@Override
public int compareTo(Song o) {
return (play == o.play) ? id - o.id : o.play - play;
}
}
public int[] solution(String[] genres, int[] plays) {
Map<String, Genre> play_map = new HashMap<>();
Genre temp;
for(int i = 0 ; i < genres.length ; i++){
if(!play_map.containsKey(genres[i])) play_map.put(genres[i], new Genre(genres[i]));
temp = play_map.get(genres[i]);
temp.addSong(new Song(i,plays[i]));
}
List<Genre> sorted_genre =
play_map.values().stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
List<Song> sorted_song;
List<Integer> res = new ArrayList<>();
for(int i = 0 ; i < play_map.size() ; i++){
System.out.println(sorted_genre.get(i).name);
sorted_song = sorted_genre.get(i).songs;
sorted_song.sort(Comparator.naturalOrder());
for(int j = 0 ; j < sorted_song.size() ; j++){
if(j == 2) break;
res.add(sorted_song.get(j).id);
}
}
int[] answer = new int[res.size()];
for(int i = 0 ; i < res.size() ; i++){
answer[i] = res.get(i);
}
return answer;
}
}
'JAVA > Coding Test' 카테고리의 다른 글
[JAVA] 프로그래머스 디스크 컨트롤러_우선순위큐 (0) | 2024.10.28 |
---|---|
[JAVA] 프로그래머스 가장 먼 노드_그래프 (0) | 2024.10.16 |
[JAVA] 프로그래머스 이중우선순위큐_힙 (0) | 2024.10.15 |
[JAVA] 프로그래머스 당구 연습_구현 (0) | 2024.10.14 |
[JAVA] 프로그래머스 유사 칸토어 비트열_분할정복 (1) | 2024.10.10 |