Algorithm/Programmers
[Algorithm][Programmers] 베스트엘범 (Java)
Jyuni
2023. 8. 20. 23:47
문제 출처 : https://school.programmers.co.kr/learn/courses/30/lessons/42579
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 설명
스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.
- 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
- 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
- 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.
노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.
입출력 예시
풀이
순차적으로 풀면
- 장르 별 총 play 수를 구한다 (HashMap 사용)
- ArrayList에 담고 play 순으로 정렬한다. (compareTo를 활용)
- play 수가 많은 장르부터 for문으로 plays를 전체 탐색하여 index를 구한다. (ArraysList 활용하여 정렬)
- 구한 값을 return 해준다.
이 순서로 풀이하였습니다.
Music 클래스를 만들고 생성자는 필요한 데이터만 가질 수 있도록 2개를 만들어서 활용하였습니다.
코드
import java.util.*;
class Solution {
public class Music implements Comparable<Music>{
int index;
String genre;
int plays;
Music(String genre, int plays) {
this.genre = genre;
this.plays = plays;
}
Music(int index, int plays) {
this.index = index;
this.plays = plays;
}
@Override
public int compareTo(Music music) {
return music.plays - this.plays;
}
}
public int[] solution(String[] genres, int[] plays) {
// 장르별 총 plays를 구하기 위한 map 선언 후 삽입
HashMap<String, Integer> stream = new HashMap<>();
for(int index = 0; index < genres.length; index++) {
stream.put(genres[index], stream.getOrDefault(genres[index], 0) + plays[index]);
}
// 정렬을 위해 ArrayList선언
ArrayList<Music> musicList = new ArrayList<>();
for(String key : stream.keySet()) {
musicList.add(new Music(key, stream.get(key)));
}
Collections.sort(musicList);
// 총 play 수가 많은 순부터 같은 장르가 있으면 Arraylist에 넣고 정렬 후
// 0,1에 해당하는 인덱스 albumNum에 삽입 (단 size가 1일 경우엔 0번 인덱스만 삽입)
ArrayList<Integer> albumNum = new ArrayList<>();
for(Music music : musicList) {
ArrayList<Music> musicPlay = new ArrayList<>();
for(int index = 0; index < genres.length; index++) {
if(music.genre.equals(genres[index])) {
musicPlay.add(new Music(index, plays[index]));
}
}
Collections.sort(musicPlay);
albumNum.add(musicPlay.get(0).index);
if(musicPlay.size() >= 2) {
albumNum.add(musicPlay.get(1).index);
}
}
// albumNum 크기만큼 answer배열 선언 후 차례대로 삽입
int[] answer = new int[albumNum.size()];
int index = 0;
for(int num : albumNum) {
answer[index++] = num;
}
return answer;
}
}