Coding Test
[프로그래머스] 베스트앨범
상상쓰
2021. 7. 29. 10:55
https://programmers.co.kr/learn/courses/30/lessons/42579?language=java
코딩테스트 연습 - 베스트앨범
스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가
programmers.co.kr
정렬을 통하여 문제를 해결하였다.
playsIndex 는 [재생 횟수, 고유번호] 로 이루어진 2차원 배열이다. palysIndex 를 재생 횟수를 기준으로 내림차순, 고유번호를 기준으로 오름차순 하여 map2 에 값을 넣을 때, 같은 고유번호라도 우선순위가 조건에 맞도록 하기 위해서다.
map 은 어떤 genre 가 재생 횟수가 가장 많은지에 대한 정보를 담고 있으므로 map 의 key 를 정렬하여 map2 에서 각 genre 에 우선순위에 맞게 정렬된 고유번호를 최대 2개 뽑아서 answer 에 담는다.
다음 answer 을 int[] 배열로 변환하여 return 해준다.
import java.util.*;
class Solution {
public int[] solution(String[] genres, int[] plays) {
List<Integer> answer = new ArrayList<>();
int[][] playsIndex = new int[plays.length][2];
for (int i=0;i<plays.length;i++) {
playsIndex[i][0] = plays[i];
playsIndex[i][1] = i;
}
Arrays.sort(playsIndex, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] == o2[0]) {
return o1[1] - o2[1];
} else {
return o2[0] - o1[0];
}
}
});
HashMap<String, Integer> map = new HashMap<>();
HashMap<String, List<Integer>> map2 = new HashMap<>();
for (int i=0;i<playsIndex.length;i++) {
if (map.containsKey(genres[playsIndex[i][1]])) {
map.put(genres[playsIndex[i][1]], map.get(genres[playsIndex[i][1]]) + playsIndex[i][0]);
map2.get(genres[playsIndex[i][1]]).add(playsIndex[i][1]);
} else {
map.put(genres[playsIndex[i][1]], playsIndex[i][0]);
List<Integer> list = new ArrayList<Integer>();
list.add(playsIndex[i][1]);
map2.put(genres[playsIndex[i][1]], list);
}
}
List<String> keySetList = new ArrayList<>(map.keySet());
Collections.sort(keySetList, (o1, o2) -> (map.get(o2).compareTo(map.get(o1))));
for (String key : keySetList) {
int cnt = 0;
for (int i : map2.get(key)) {
cnt++;
answer.add(i);
if (cnt == 2) {
break;
}
}
}
return answer.stream().mapToInt(i -> i).toArray();
}
}