계단을 오르듯이

[JAVA] 프로그래머스_베스트 앨범 본문

알고리즘/프로그래머스

[JAVA] 프로그래머스_베스트 앨범

happyAyun 2022. 1. 12. 07:47

적절한 자료구조를 생각해야했고, 나는 HashMap과 ArrayList를 이용하였다.

적절한 오름차순의 정렬을 통해 순차적으로 문제를 풀어나갔다.

역시 알고리즘은 맞나..? 고민하지 말고 우선 해보는 시도가 나아가는 발걸음이다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.*;
 
class Solution {
    public int[] solution(String[] genres, int[] plays) {
        int[] answer = {};
        int len = genres.length;
        Map<String, Integer> map = new HashMap<>();
        List<Node> musicList = new ArrayList<>();
        // 장르 재생횟수 더하기
        for(int i=0;i<len;i++){
            if(map.containsKey(genres[i])){
                map.replace(genres[i], map.get(genres[i])+plays[i]);
            }else
                map.put(genres[i], plays[i]);
            musicList.add(new Node(genres[i], i, plays[i]));
        }
        Collections.sort(musicList);
        
        // 우선순위 장르 구하고 결과값 입력하기
        List<Integer> result = new ArrayList<>(); // answer
        int count = 0// 연산의 횟수 while문을 빠져나가기 위해
        int size = map.size();
        while(size > count++){
            List<String> keyList = new ArrayList<>(map.keySet()); // key로 리스트 만들기
            int maxNum = 0;
            String maxGen = "";
            for(String key : keyList){
                if(maxNum < map.get(key)){
                    maxNum = map.get(key);
                    maxGen = key;
                }
            }
            map.remove(maxGen);
            int siz = musicList.size();
            int cnt = 0// 최대 2곡 선택 가능
            for(int i=0;i<siz;i++){
                if(musicList.get(i).gen.equals(maxGen)){
                    result.add(musicList.get(i).idx);
                    cnt++;
                }
                if(cnt >= 2break;
            }
        }
        // answer
        size = result.size();
        answer = new int[size];
        for(int i=0;i<size;i++){
            answer[i] = result.get(i);
        }
        return answer;
    }
    
    static class Node implements Comparable<Node>{
        String gen;
        int idx, num;
        
        public Node(String gen, int idx, int num){
            super();
            this.gen = gen;
            this.idx = idx;
            this.num = num;
        }
        
        @Override
        public int compareTo(Node o){ // 내림차순 정렬
            return Integer.compare(o.num, this.num);
        }
    } 
}
cs