-
[프로그래머스] 베스트앨범 - 해시코딩테스트 문제풀이 2021. 10. 2. 16:25
문제
풀이
import java.util.*; class Solution { public int[] solution(String[] genres, int[] plays) { int[] answer = {}; List<Integer> answerList = new ArrayList<Integer>(); Map<String, Integer> genresPlayCount = new HashMap<String, Integer>(); for (int i = 0; i < genres.length; i++) { String genre = genres[i]; int playCount = plays[i]; genresPlayCount.put(genre, genresPlayCount.getOrDefault(genre, 0) + playCount); } List<String> genreRankList = new ArrayList<String>(genresPlayCount.keySet()); Collections.sort(genreRankList, (o1, o2) -> (genresPlayCount.get(o2)-genresPlayCount.get(o1))); for (String genre : genreRankList) { Map<Integer, Integer> songIndexMap = new HashMap<Integer, Integer>(); for (int i = 0; i < genres.length; i++) { if (genres[i].equals(genre)) { songIndexMap.put(i, plays[i]); } } List<Integer> idxList = new ArrayList<Integer>(songIndexMap.keySet()); Collections.sort(idxList, (o1, o2) -> (songIndexMap.get(o2)-songIndexMap.get(o1))); answerList.add(idxList.get(0)); if (idxList.size() > 1) answerList.add(idxList.get(1)); } answer = new int[answerList.size()]; for (int i = 0; i < answerList.size(); i++) { answer[i] = answerList.get(i); } return answer; } }
- genres[]를 장르별로 play 횟수를 모두 더해 HashMap 생성한다. (genresPlayCount)
- genresPlayCount를 playCount 내림차순으로 정렬한다.
- genresPlayCount의 genre별 play가 가장 많이된 곡의 idx를 HashMap 생성한다.(songIdxMap)
- songIdxMap을 playCount 내림차순 정렬한다.
- 최대 2곡까지 answer 배열에 추가한다.
출처: https://programmers.co.kr/learn/courses/30/lessons/42579
'코딩테스트 문제풀이' 카테고리의 다른 글
[프로그래머스] 야근지수 (0) 2021.10.06 [백준 2798] 블랙잭 (0) 2021.10.06 [백준 11279] 최대힙 - 우선순위 큐 (0) 2021.10.02 [프로그래머스] 소수 찾기 - 완전탐색 (0) 2021.10.02 [백준 2231] 분해합 (0) 2021.09.22