Lv 3. 베스트 앨범

2024. 10. 2. 16:44·Algorithm & Data Structures/Programers

https://school.programmers.co.kr/learn/courses/30/lessons/42579?language=java

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

HashMap을 활용하여 Genre가 이미 존재하는지 확인하고
Music은 새로 받을때마다 하나의 객체를 만들어주고
Genre에 존재하는 pq에 집어넣어주면서 자동정렬해주었다.
관건은 HashMap을 정렬하는데서 오류가 발생하였고
Collections.sort로 정렬하려 하였으나 Map과 Set같은 경우
List 형태가 아니어서 정렬이 불가능하다는것을 알았다.
HashMap에 존재하는 values() Method를 활용하여
List로 장르를 받아주고 그상태로 정렬하였다. 어차피 장르의
번호나 이름은 중요하지 않았기에 가능했다.

 
// 장르별 두곡 모아 베스트 앨범 출시
// class genre {
// class music 사용
import java.util.*;

class Solution {
    class Genre {
        int totPlays = 0; 
        PriorityQueue<Music> pq = new PriorityQueue<>((m1, m2) -> {
            if (m1.plays == m2.plays) 
                return m1.id - m2.id; 
            return m2.plays - m1.plays; 
        });
        public void add(Music m) {
            pq.add(m);
            totPlays += m.plays;
        }
    }
    class Music {
        int id; 
        int plays;
        public Music(int id, int plays) {
            this.id = id;
            this.plays = plays;
        }
    }
    public int[] solution(String[] genres, int[] plays) {
        HashMap<String, Genre> map = new HashMap<>();
        for (int i = 0; i < genres.length; i++) {
            map.putIfAbsent(genres[i], new Genre());
            map.get(genres[i]).add(new Music(i, plays[i]));
        }
        List<Genre> sorted = new ArrayList<>(map.values()); 
        sorted.sort((g1, g2) -> g2.totPlays - g1.totPlays);
        List<Integer> ans = new ArrayList<>(); 
        for (Genre g : sorted) {
            int cnt = 0; 
            while (!g.pq.isEmpty() && cnt < 2) {
                ans.add(g.pq.poll().id);
                cnt++;
            }
        }
        return ans.stream().mapToInt(i -> i).toArray();
    }
}

'Algorithm & Data Structures > Programers' 카테고리의 다른 글

Lv 3. 보석 쇼핑  (3) 2024.10.05
Lv 3. 스티커 모으기  (2) 2024.10.03
Lv 2. 다리를 지나는 트럭  (0) 2024.10.01
Lv 3. 기지국 설치  (0) 2024.09.30
Lv 3. 단속카메라  (1) 2024.09.29
'Algorithm & Data Structures/Programers' 카테고리의 다른 글
  • Lv 3. 보석 쇼핑
  • Lv 3. 스티커 모으기
  • Lv 2. 다리를 지나는 트럭
  • Lv 3. 기지국 설치
Geisha
Geisha
개발 일기
  • Geisha
    Geisha
    Geisha
  • 전체
    오늘
    어제
    • 분류 전체보기 (311) N
      • Algorithm & Data Structures (235) N
        • BOJ (93) N
        • SWEA (1)
        • Programers (137) N
        • Data Structures (3)
      • DB (23) N
        • SQL (17) N
        • RDBMS (2)
      • Java (1)
        • Class (1)
      • Spring (5)
        • Spring MVC (1)
        • Annotations (1)
      • CS (36)
        • 운영체제 (13)
        • 네트워크 (5)
      • Tool (6)
        • Git (5)
        • AWS (1)
      • Project (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준
    구현
    백트래킹
    Dijkstra
    후위순회
    Java
    스택
    골드
    이분탐색
    알고리즘
    dp
    프로그래머스
    유니온파인드
    Stack
    SQL
    unionfind
    dfs
    algorithm
    DynamicProgramming
    BFS
    programmers
    PriorityQueue
    투포인터
    baekjoon
    다익스트라
    동적계획법
    binarySearch
    경로압축
    Union-Find
    전위순회
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
Geisha
Lv 3. 베스트 앨범
상단으로

티스토리툴바