[코딩테스트]/[프로그래머스]

[프로그래머스] C# 문제풀이 27. 해시 - 베스트앨범

극꼼 2022. 5. 25. 12:43
반응형


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

 

코딩테스트 연습 - 베스트앨범

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가

programmers.co.kr


문제 설명)

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.

  1. 속한 노래가 많이 재생된 장르를 먼저 수록합니다.
  2. 장르 내에서 많이 재생된 노래를 먼저 수록합니다.
  3. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.

노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.

 

제한사항)
  • genres[i]는 고유번호가 i인 노래의 장르입니다.
  • plays[i]는 고유번호가 i인 노래가 재생된 횟수입니다.
  • genres와 plays의 길이는 같으며, 이는 1 이상 10,000 이하입니다.
  • 장르 종류는 100개 미만입니다.
  • 장르에 속한 곡이 하나라면, 하나의 곡만 선택합니다.
  • 모든 장르는 재생된 횟수가 다릅니다.

Dictionary를 이용해 풀었는데요, 장르를 Key에, 재생 횟수를 play 클래스로 만들어 Value에 넣었습니다.

play클래스는 가장 많이 재생된 횟수와 index를 2개 저장하고, 리스트로 만들어질 경우 전체 재생 횟수인 allCount를 기준으로 정렬합니다. 

public class play : IComparable
{
    public int allCount = 0;
    public int count1 = 0;
    public int count2 = 0;
    public int index1 = -1;
    public int index2 = -1;
    public void InputList(int _count, int _index)
    {
        allCount += _count;
        if (_count >= count1)
        {
            count2 = count1;
            count1 = _count;
            index2 = index1;
            index1 = _index;
            if(count1 == count2 && index1 > index2)
            {
                int temp = index2;
                index2 = index1;
                index1 = temp;
            }
        }
        else if(_count > count2)
        {
            count2 = _count;
            index2 = _index;
        }
        else if(_count == count2 && index2 > _index)
        {
            index2 = _index;
        }
    }
    public int CompareTo(object obj)
    {
        play p = obj as play;
        return -allCount.CompareTo(p.allCount);
    }
}

public class Solution
{
    public int[] solution(string[] genres, int[] plays)
    {
        List<int> answer = new List<int>();
        Dictionary<string, play> streamList = new Dictionary<string, play>();
        for (int i = 0; i < genres.Length; i++)
        {
            if (streamList.ContainsKey(genres[i]))
            {
                streamList[genres[i]].InputList(plays[i], i);
            }
            else
            {
                play p = new play();
                p.InputList(plays[i], i);
                streamList.Add(genres[i], p);
            }
        }
        List <play> playList = new List<play>(streamList.Values);
        playList.Sort();
        for (int i = 0; i < playList.Count; i++)
        {
            answer.Add(playList[i].index1);
            if (playList[i].index2 != -1) answer.Add(playList[i].index2);
        }
        return answer.ToArray();
    }
}

풀이 링크 : GitHub 

 

반응형