728x90
https://school.programmers.co.kr/learn/courses/30/lessons/42579
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
🤔 문제분석
장르별로 음악을 묶는다. 장르별로 묶을때 우선순위 큐를 활용하여 묶는다. 장르별로 묶은다음 큐에서 2개씩 꺼내어 결과에 집어넣으면 된다.
💻 코드
import java.util.*;
// <https://school.programmers.co.kr/learn/courses/30/lessons/42579>
// 가장 많이 재생된 노래를 두개씩 모아 베스트 앨범을 출시
// 각 장르별로 우선순위 큐를 활용하여 최대 2개씩 뽑아야한다.
// (장르, 재생횟수), Map(장르,노래들)
class Solution {
public int[] solution(String[] genres, int[] plays) {
int[] answer = {};
Comparator comparator = (music1, music2) -> music2.plays - music1.plays;
Map<string, genre=""> map = new HashMap<>();
for(int i = 0; i < genres.length; i++)
{
Genre genre = map.getOrDefault(genres[i], new Genre(genres[i], comparator));
genre.totalPlays += plays[i];
genre.musics.add(new Music(i, plays[i]));
map.put(genres[i], genre);
}
Comparator comparator1 = (g1, g2) -> g2.totalPlays - g1.totalPlays;
PriorityQueue queue = new PriorityQueue<>(comparator1);
for(var key : map.keySet())
{
queue.add(map.get(key));
//System.out.println(String.format("genre:%s, total:%d", key, map.get(key).totalPlays));
}
List result = new ArrayList<>();
while(!queue.isEmpty()) {
Genre g = queue.poll();
for(int i =0; i < 2; i ++) {
if(!g.musics.isEmpty())
{
Music m = g.musics.poll();
result.add(m.id);
}
}
}
return result.stream().mapToInt(i -> i).toArray();
}
public static class Genre
{
public String genre;
public int totalPlays;
public PriorityQueue musics;
public Genre(String genre, Comparator comparator)
{
this.genre = genre;
this.totalPlays = 0;
this.musics = new PriorityQueue<>(comparator);
}
}
public static class Music
{
public int id;
public int plays;
Music(int id, int plays)
{
this.id = id;
this.plays = plays;
}
@Override
public String toString() {
return String.format("id:%d, plays:%d", id, plays);
}
}
}
</string,>
728x90
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 이중우선순위큐 (0) | 2024.04.13 |
---|---|
[프로그래머스] 전력망을 둘로 나누기 (0) | 2024.04.13 |
[프로그래머스] 완주하지 못한선수 (0) | 2024.04.10 |
[프로그래머스] 퍼즐조각 채우기 (0) | 2024.04.10 |
[프로그래머스] 2023 Kakao Blind Recruitment : 표병합 (0) | 2023.11.22 |