[프로그래머스] 베스트 앨범 자바 level3

Jifrozen·2023년 1월 8일
0

Algorithm

목록 보기
68/70

https://school.programmers.co.kr/learn/courses/30/lessons/42579

문제

레벨 3이지만 어려운 문제는 아니였다.
1. 노래는 고유 번호와 장르 재생 시간을 가진다.
2. 장르 별로 가장 많이 재생된 노래를 2개 씩 모아야 한다.
우선순위
- 많이 재생된 장르
- 장르 내에서 많이 재생된 노래
- 고유번호가 낮은 노래

  1. 1번째 우선순위인 많이 재생된 장르를 알아내기 위해 HashMap을 사용했다.
    장르는 정해진게 없이 무작위로 생기기 때문에 getOrDefault를 통해 HashMap에 add해줬다. HashMap에 전부 집어넣으면 재생순으로 내림차순 정렬을 진행했다.
HashMap<String,Integer> map=new HashMap<>();

        for(int i=0;i<genres.length;i++){
            map.put(genres[i],map.getOrDefault(genres[i],0)+plays[i]);
        }

        ArrayList<String> keyArr=new ArrayList(map.keySet());
        Collections.sort(keyArr,(s1,s2)->map.get(s2)-map.get(s1));

["classic", "pop", "classic", "classic", "pop"][500, 600, 150, 800, 2500]에서 우선순위가
classic 장르는 1,450회 재생 / pop 장르는 3,100회 재생
pop이 먼저이다.

  1. 다음 우선순위인 장르 내에서 많이 재생된 노래와 고유번호순으로 정렬하기 위해 노래 객체를 따로 만들어 Comparable을 구현했다.
 class Album implements Comparable<Album>{
        int index;
        int plays;
        String genre;
        public Album(int index,int plays,String genre){
            this.index=index;
            this.plays=plays;
            this.genre=genre;
        }

        @Override
        public int compareTo(Album other){
            if(this.plays==other.plays){
                return this.index-other.index;
            }
            return other.plays-this.plays;
        }
    }
  1. 우선순위에 맞게 answer 배열에 집어넣기
 Collections.sort(albums);// 해당 노래들 우선순위 2 3순위 기준으로 정렬
 for(String key:keyArr){//우선순위 장르만큼 반복
            int check=0;
            for(int i=0;i<albums.size();i++){// 앨범 반복
                if(key.equals(albums.get(i).genre)){//장르 같으면 - 1번쨰 우선순위
                    if(check>=2) break;//2개 체크
                    check++;
                    answer.add(albums.get(i).index);//집어넣기
                }
            }
        }

        return answer.stream().mapToInt(i -> i).toArray();

코드

import java.util.*;
class Solution {
    class Album implements Comparable<Album>{
        int index;
        int plays;
        String genre;
        public Album(int index,int plays,String genre){
            this.index=index;
            this.plays=plays;
            this.genre=genre;
        }

        @Override
        public int compareTo(Album other){
            if(this.plays==other.plays){
                return this.index-other.index;
            }
            return other.plays-this.plays;
        }
    }
    public int[] solution(String[] genres, int[] plays) {
        ArrayList<Integer> answer=new ArrayList<>();

        HashMap<String,Integer> map=new HashMap<>();
        ArrayList<Album> albums=new ArrayList<>();

        for(int i=0;i<genres.length;i++){
            map.put(genres[i],map.getOrDefault(genres[i],0)+plays[i]);
            albums.add(new Album(i,plays[i],genres[i]));
        }

        ArrayList<String> keyArr=new ArrayList(map.keySet());
        Collections.sort(albums);
        Collections.sort(keyArr,(s1,s2)->map.get(s2)-map.get(s1));

        for(String key:keyArr){
            int check=0;
            for(int i=0;i<albums.size();i++){
                if(key.equals(albums.get(i).genre)){
                    if(check>=2) break;
                    check++;
                    answer.add(albums.get(i).index);
                }
            }
        }

        return answer.stream().mapToInt(i -> i).toArray();
    }
}

2개의 댓글

comment-user-thumbnail
2023년 1월 9일

좋은 풀이네요 덕분에 getOrDefault 메서드를 알았습니다. 궁금한점이 있는데,
Collections.sort(keyArr,(s1,s2)->map.get(s2)-map.get(s1)); 여기 코드가 스트림인가요 풀어서 해석을 여쭤볼께요. ㅠ

1개의 답글