-
728x90
[ 풀이 방법 ]
- 장르별 재생 횟수를 저장해준다.
- 각 장르에 속한 노래의 <고유번호, 재생 횟수>를 저장해준다.
- 속한 노래가 많이 재생된 장르를 먼저 수록해야 하므로, 장르별 재생 횟수를 저장해준다.
- 장르 내에서 많이 재생된 노래를 먼저 수록해야 하므로, 곡 수대로 내림차순 정렬 해준다.
- 정렬된 num의 순서대로
music에서 정렬된 곡들 중 상위 2곡의 고유번호를 answer(ArrayList)에 담는다.- ArrayList를 배열로 바꾸어 리턴한다.
[ 전체 코드 ]
import java.util.*;class Solution {public int[] solution(String[] genres, int[] plays) {ArrayList<Integer> answer = new ArrayList<>();HashMap<String, Integer> num = new HashMap<>(); // 장르별 총 개수HashMap<String, HashMap<Integer, Integer>> music = new HashMap<>(); // 장르에 속하는 노래 및 재생횟수for(int i = 0; i < plays.length; i++) {if(!num.containsKey(genres[i])) {HashMap<Integer, Integer> map = new HashMap<>();map.put(i, plays[i]);music.put(genres[i], map);num.put(genres[i], plays[i]);} else {music.get(genres[i]).put(i, plays[i]);num.put(genres[i], num.get(genres[i]) + plays[i]);}}List<String> keySet = new ArrayList(num.keySet());Collections.sort(keySet, (s1, s2) -> num.get(s2) - (num.get(s1)));for(String key : keySet) {HashMap<Integer, Integer> map = music.get(key);List<Integer> genre_key = new ArrayList(map.keySet());Collections.sort(genre_key, (s1, s2) -> map.get(s2) - (map.get(s1)));answer.add(genre_key.get(0));if(genre_key.size() > 1)answer.add(genre_key.get(1));}return answer.stream().mapToInt(i -> i).toArray();}}데롱디롱희희.. (๑′ᴗ‵๑)
'알고리즘 풀이 > 프로그래머스' 카테고리의 다른 글
[level2] 프로그래머스 - 짝지어 제거하기(JAVA) (0) 2021.09.18 [level2] 프로그래머스 - 더 맵게(JAVA) (0) 2021.09.18 [level2] 프로그래머스 - 프린터(JAVA) (0) 2021.09.17 [level3] 프로그래머스 - 가장 먼 노드(JAVA) (0) 2021.09.17 [level3] 프로그래머스 - 순위(JAVA) (0) 2021.09.17