[프로그래머스]해시-베스트앨범

snusun·2021년 1월 28일
0

알고리즘

(1) 해시에 장르를 key로, 총 재생횟수를 value로 넣는다.
(2) 재생 횟수가 가장 많은 ganre부터 재생횟수 top2인 노래를 골라 앨범에 넣는다.

import java.util.*;

class Solution {
    public int[] solution(String[] genres, int[] plays) {
        HashMap<String, Integer> album = new HashMap<>();
        ArrayList<Integer> idx = new ArrayList<>();
        ArrayList<Integer> bestAlbum = new ArrayList<>();

        for(int i=0; i< genres.length; i++){
            if(album.containsKey(genres[i])){
                album.replace(genres[i], album.get(genres[i])+plays[i]);
            } else {
                album.put(genres[i], plays[i]);
            }
        }

        while(!album.isEmpty()){
            int max = 0;
            String maxGanre = "";
            for(String s : album.keySet()){ //maxGanre 선택
                if(max < album.get(s)) {
                    max = album.get(s);
                    maxGanre = s;
                }
            }

            for(int i=0; i<genres.length; i++){ //해당 장르인 노래 idx 선택
                if(genres[i].equals(maxGanre)){
                    idx.add(i);
                }
            }

            int k=0;
            while(!idx.isEmpty() && k<2){ //재생횟수 상위 2개의 idx 구해서 앨범에 추가 (횟수 같으면 idx 낮은 것부터)
                int ganreMax=0;
                int ganreIdx=0;

                for(int temp=0; temp<idx.size(); temp++){
                    if(ganreMax < plays[idx.get(temp)]){
                        ganreMax = plays[idx.get(temp)];
                        ganreIdx = temp;
                    }
                }

                bestAlbum.add(idx.remove(ganreIdx));
                k++;
            }

            album.remove(maxGanre); //remove max ganre
            idx.clear();
        }

        int[] array = new int[bestAlbum.size()];
        int size=0;
        for(int temp : bestAlbum){
            array[size++] = temp;
        }

        return array;
    }
}
profile
대학생 근데 이제 컴공을 곁들인

0개의 댓글