Step-by-Step

[Java] 프로그래머스 - 베스트앨범 (+Comparable 사용) 본문

언어/JAVA

[Java] 프로그래머스 - 베스트앨범 (+Comparable 사용)

희주(KHJ) 2022. 11. 13. 22:54

https://school.programmers.co.kr/learn/courses/30/lessons/42579

 

프로그래머스

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

programmers.co.kr

프로그래머스는 문제 유형이 뭔지 알려준다.

Hash 쓰는거길래 재밌을거 같아서 시도해보았다.

 

 

※ TIP

  • Comparable을 꼭 이용하자!!!!!!

https://smile-development.tistory.com/92

 

Comparable 사용하기

List 같은 곳에 요소들을 넣을 때, 매번 비교하고 넣으면 코드가 너무 지저분해진다. 그럴때 사용하는거 Comparable! Comparable 객체 간 비교를 가능하게 해주는 인터페이스 (→사용시 구현해야 함) 구

smile-development.tistory.com

 

 

인터페이스 없이 사용하려다가  해시 지옥을 맛봤다.. 오히려 돌아가는 일이니 그러지말자......

 

 

[코드]

import java.util.*;

class Solution {
    class Music implements Comparable<Music>{
        String genre;
        int index, play;
        
        public Music(String genre, int index, int play){
            this.genre = genre;
            this.index = index;
            this.play = play;
        }
        
        @Override
		public int compareTo(Music o) {
            
			if(this.play == o.play){
                return this.index - o.index;
            }
            
			return o.play - this.play;
		}
    }
    
    public int[] solution(String[] genres, int[] plays) {
        ArrayList<Integer> arr = new ArrayList<>();
        HashMap<String, Integer> sum = new HashMap<>();
        HashMap<String, PriorityQueue<Music>> list = new HashMap<>();
        HashSet<String> genreList = new HashSet<>();
        
        for(int i=0; i<genres.length; i++){
            String g = genres[i];
            int p = plays[i];
            
            // 총합 넣기
            sum.put(g, sum.getOrDefault(g,0)+p);
            
            // play 큰 수 -> index 작은 순
            PriorityQueue<Music> pq = list.getOrDefault(g, new PriorityQueue<>());
            pq.add(new Music(g, i, p));
            list.put(g, pq);
            
            genreList.add(g);
        }
        
        
        PriorityQueue<String> pq = new PriorityQueue<>((String s1, String s2)->(sum.get(s2)-sum.get(s1)));
        for(String g : genreList){
            pq.add(g);
        }
        
        while(!pq.isEmpty()){
            String g = pq.poll();
            PriorityQueue<Music> m = list.get(g);
            
            if(m.size()==1){
                arr.add(m.poll().index);
                continue;
            }
            
            arr.add(m.poll().index);
            arr.add(m.poll().index);
        }
        
        int[] ans = new int[arr.size()];
        for(int i=0; i<arr.size(); i++){
            ans[i] = arr.get(i);
        }
               
        return ans;
    }
}

'언어 > JAVA' 카테고리의 다른 글

[Java] 백준 1522 - 문자열 교환  (0) 2022.11.27
[Java] 백준7579 - 앱  (0) 2022.11.14
Comparable & Comparator 사용하기  (0) 2022.11.13
[Java] 백준11758 - CCW  (0) 2022.11.12
[Java] 백준9376 - 탈옥  (1) 2022.11.12
Comments