프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
뭐 특별한 알고리즘이나 자료구조를 사용할 것도 없이 요구사항만 구현하면 된다.
입력받은 두 배열로 Dictionary를 만든다.
Dictionary는 장르와 해당 장르의 총합, 제일 많이 플레이된 노래, 두번째로 많이 플레이된 노래를 가진다.
다음은 장르들을 총합으로 정렬하고 순서대로 answer에 추가해준다.
answer는 배열 형태인데, 배열의 크기를 미리 정할 수 없어서 List<int> 형태로 먼저 만들고 array로 변환했다.
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int[] solution(string[] genres, int[] plays)
{
int[] answer = new int[] { };
Dictionary<string, (int total, int first, int second)> map = new Dictionary<string, (int total, int first, int second)>();
for (var i = 0; i < genres.Length; i++)
{
if (map.ContainsKey(genres[i]))
{
var value = map[genres[i]];
value.total += plays[i];
if (plays[i] > plays[value.first])
{
value.second = value.first;
value.first = i;
}
else if (value.second == -1 || plays[i] > plays[value.second])
{
value.second = i;
}
map[genres[i]] = value;
}
else
{
map.Add(genres[i], (plays[i], i, -1));
}
}
List<(int total, int first, int second)> values = map.Values.ToList();
values.Sort((l, r) =>
{
return r.total.CompareTo(l.total);
});
List<int> temp = new List<int>();
for (var i = 0; i < values.Count; i++)
{
temp.Add(values[i].first);
if (values[i].second != -1)
temp.Add(values[i].second);
}
answer = temp.ToArray();
return answer;
}
}
'코딩연습' 카테고리의 다른 글
(javascript) 도둑질 (0) | 2025.07.03 |
---|---|
(C#) N으로 표현 (0) | 2025.06.30 |
(C#) 지형 이동 (0) | 2025.06.16 |
(C#) 섬 연결하기 (0) | 2025.06.13 |
(C#) 쿠키 구입 (0) | 2025.06.12 |