문제 풀기/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;
    }
}

'문제 풀기 > C#' 카테고리의 다른 글

85. 연속 부분 수열 합의 개수  (0) 2025.03.04
84. 괄호 회전하기  (0) 2025.03.04
82. 멀리 뛰기  (0) 2025.02.28
81. N개의 최소공배수  (0) 2025.02.28
80. 예상 대진  (0) 2025.02.28