문제 풀기/C#
83. 귤 고르기 (Dictionary 요소 정렬)
kagan-draca
2025. 3. 4. 14:50
기본 틀 :
using System;
public class Solution {
public int solution(int k, int[] tangerine) {
int answer = 0;
return answer;
}
}
문제를 푸는 방법으로 여러가지가 존재하겠지만
딕셔너리를 활용하여 tangerine의 크기 별 개수를 구하고
딕셔너리를 내림차순 정리 후 k와 비교하여 몇 개의 크기가 필요한지 구했다.
using System;
using System.Linq;
using System.Collections.Generic;
public class Solution {
public int solution(int k, int[] tangerine)
{
Dictionary<int,int> dict = new Dictionary<int,int>();
int count = 0;
for(int i = 0; i < tangerine.Length; i++)
{
if(!dict.ContainsKey(tangerine[i])) dict.Add(tangerine[i], 1);
else dict[tangerine[i]]++;
}
dict = dict.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x=> x.Value);
foreach(int key in dict.Keys)
{
count++;
if(k - dict[key] <= 0)
break;
else
k -= dict[key];
}
return count;
}
}