|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class PGM_LV2_베스트엘범 { |
| 5 | + |
| 6 | + private static int len; |
| 7 | + |
| 8 | + private static Map<String, Queue<Node>> order; |
| 9 | + private static Map<String, Integer> cnt; |
| 10 | + |
| 11 | + private static class Node implements Comparable<Node> { |
| 12 | + int id; |
| 13 | + int cnt; |
| 14 | + |
| 15 | + Node(int id, int cnt) { |
| 16 | + this.id = id; |
| 17 | + this.cnt = cnt; |
| 18 | + } |
| 19 | + |
| 20 | + @Override |
| 21 | + public int compareTo(Node o) { |
| 22 | + return Integer.compare(o.cnt, this.cnt); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public int[] solution(String[] genres, int[] plays) { |
| 27 | + len = genres.length; |
| 28 | + |
| 29 | + order = new HashMap<>(); |
| 30 | + cnt = new TreeMap<>(Collections.reverseOrder()); |
| 31 | + |
| 32 | + for (int i = 0; i < genres.length; i++) { |
| 33 | + cnt.put(genres[i], cnt.getOrDefault(genres[i], 0) + plays[i]); |
| 34 | + |
| 35 | + order.putIfAbsent(genres[i], new PriorityQueue<>()); |
| 36 | + order.get(genres[i]).offer(new Node(i, plays[i])); |
| 37 | + } |
| 38 | + |
| 39 | + List<String> sortedGenres = new ArrayList<>(order.keySet()); |
| 40 | + sortedGenres.sort((a, b) -> Integer.compare(cnt.get(b), cnt.get(a))); |
| 41 | + |
| 42 | + List<Integer> res = new ArrayList<>(); |
| 43 | + |
| 44 | + for (String genre : sortedGenres) { |
| 45 | + Queue<Node> pq = order.get(genre); |
| 46 | + |
| 47 | + for (int i = 0; i < 2 && !pq.isEmpty(); i++) { |
| 48 | + res.add(pq.poll().id); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return res.stream().mapToInt(i -> i).toArray(); |
| 53 | + } |
| 54 | +} |
| 55 | +``` |
0 commit comments