import java.util.*;
class Solution {
public int[] solution(String[] genres, int[] plays) {
int[] answer = new int[genres.length];
Map<String, List<Node>> map = new HashMap();
for (int i = 0; i < plays.length; i++) {
if (!map.containsKey(genres[i])) {
map.put(genres[i], new ArrayList<>());
}
map.get(genres[i]).add(new Node(genres[i],i, plays[i]));
}
Queue<Node> queue = new PriorityQueue<>((a, b) -> b.sum-a.sum);
for (String key : map.keySet()) {
int sum = map.get(key).stream().map(m -> m.sum).mapToInt(i -> i).sum();
queue.offer(new Node(key,0,sum));
}
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
Node node = queue.poll();
List<Node> nodes = map.get(node.genreName);
Collections.sort(nodes,(a,b)->b.sum-a.sum);
for (int i = 0; i < 2 && !nodes.isEmpty() ; i++) {
Node remove = nodes.remove(0);
list.add(remove.index);
}
}
return list.stream().mapToInt(i -> i).toArray();
}
static class Node {
String genreName;
int index;
int sum;
public Node(String genreName,int index, int sum) {
this.genreName =genreName;
this.sum = sum;
this.index = index;
}
}
}
장르별로 맵에 값을 저장한다. 이 때 Node라는 클래스를 만들어 장르,순서,플레이 수를 저장한다.
장르별로 합계를 구한다. 이 후 합계를 우선순위 큐에 집어넣는다.
큐에는 현재 총합 내리차순 순으로 저장 되어 있는데 이것을 큐가 빌 때까지 꺼낸다. 꺼낸 값에는 해당 장르별 값들이 저장되어 있는데 이 값들을 다시 정렬하는데 이 때 플레이수를 기준으로 내림차순으로 정렬한다. 만약 값이 같다면 인덱스 오르차순순으로 정렬하게 설정한다.
이 후 answer값을 배열로 변환하여 반환한다.
처음에는 IDE없이 풀려고 하였는데 코드를 짜다 보니 map과 stream에 아직 익숙하지 않고 특히 괄호 때문에 풀고 테스트하는 것이 힘들어 IDE의 힘을 빌려 풀었다.
출처 : 프로그래머스 - 베스트 앨범