[programmers] 베스트 앨범

JongSeong Yang·2021년 5월 7일

programmers

목록 보기
7/16

문제 풀이 : 2021.05.07

풀이

주어진 데이터들을 genres를 key값으로 하여 hashmap을 만들어야 함
hashmap에 이미 있는 genre면 해당 value에 추가해야 함
value 값에 따라 keySet을 정렬하기 위해 arrayList를 이용함
정렬한 list에서 plays 배열을 순회하면서 max와 두번째 max를 구함
구한 인덱스를 arrayList에 넣고 마지막에 int[] 로 바꿔서 반환

코드

import java.util.*;
class Solution {
    HashMap<String, Integer> g = new HashMap<>();
    ArrayList<Integer> answer = new ArrayList<>();
    
    public int[] solution(String[] genres, int[] plays) {
        for(int i = 0;i<genres.length;i++){
            g.put(genres[i], g.getOrDefault(genres[i],0)+plays[i]);
        }
        ArrayList<String> keySets = new ArrayList<>(g.keySet());
        Collections.sort(keySets,(o1, o2) -> (g.get(o2).compareTo(g.get(o1))));
        
        for(String s : keySets){
            int first = 0;
            int second = 0;
            int Max = -1;
            for(int i = 0;i<plays.length;i++){
                if(s.equals(genres[i])){
                    if(Max<plays[i]){
                        Max = plays[i];
                        first = i;
                    }
                }
            }
            Max = -1;
            for(int i = 0;i<plays.length;i++){
                if(i!= first && s.equals(genres[i])){
                    if(Max<plays[i]){
                        Max = plays[i];
                        second = i;
                    }
                }
            }
            answer.add(first);
            if(Max!=-1) answer.add(second);
        }
        return answer.stream().mapToInt(i->i).toArray();
    }
}

문제 출처 링크

profile
꿈꾸는 개발자

0개의 댓글