글 작성자: Doublsb

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

 

풀이

- 장르 별로 가장 많이 재생된 두 곡 모으기

- 가장 많이 재생된 장르 => 장르 내에서 가장 많이 재생된 노래 => 고유 번호가 낮은 노래 먼저 수록

 

- 해시테이블 안에 장르 클래스를 넣는 것이다

- 장르 클래스에는 재생 횟수, 2개의 노래 클래스가 들어간 리스트가 만들어짐

- 노래 클래스에는 재생 횟수와 고유 번호가 존재한다

 

- 장르 클래스에서 음악을 재생시킬 때, 재생 횟수를 비교하여 리스트를 갱신한다

 

- LinQ를 이용하여 장르 클래스의 재생 횟수가 높은 순서대로 수행

- 2개의 노래 클래스에서 각 고유 번호를 리턴한다

 

C#

using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    
    public Dictionary<string, Genre> DB
        = new Dictionary<string, Genre>();
    
    public int[] solution(string[] genres, int[] plays) {
        
        for(int i=0; i<genres.Length; i++){
            if(!DB.ContainsKey(genres[i]))
                DB.Add(genres[i], new Genre());

            DB[genres[i]].Play(new Song(i, plays[i]));
        }
        
        List<int> answer = new List<int>();
        foreach(var data in DB.Values.OrderByDescending(e => e.PlayCount)){
            foreach(var song in data.BestSongs){
                answer.Add(song.Number);
            }
        }

        return answer.ToArray();
    }
}

public class Genre {
    public int PlayCount;
    public List<Song> BestSongs;
    
    public Genre(){
        PlayCount = 0;
        BestSongs = new List<Song>();
    }
    
    public void Play(Song song){

        PlayCount += song.PlayCount;
        int index = Get_IndexOfBestSong(song);
   
        if(index != -1) {
            BestSongs.Insert(index, song);
        }
        
        if(BestSongs.Count > 2) {
            BestSongs.RemoveAt(BestSongs.Count - 1);
        }
    }
    
    public int Get_IndexOfBestSong(Song song){

        for(int i=0; i<BestSongs.Count; i++){
            if(BestSongs[i].PlayCount < song.PlayCount){
                return i;
            }
            else if(BestSongs[i].PlayCount == song.PlayCount){
                return BestSongs[i].Number > song.Number ? i : i+1;
            }
        }
        
        return BestSongs.Count;
    }
}

public class Song {
    public int Number;
    public int PlayCount;
    
    public Song(int number, int playcount){
        Number = number;
        PlayCount = playcount;
    }
}

 

결과

100.0 / 100.0

 

피드백

어려운 문제는 LinQ 덕분에 아니었음. 하하 LinQ 만세 하하

반응형