백준 등 알고리즘

[C#] 프로그래머스 Lv.2 귤 고르기

박도치 2024. 11. 21. 20:46

https://school.programmers.co.kr/learn/courses/30/lessons/138476

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

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

public class Solution
{
    public int solution(int k, int[] tangerine)
    {
        // size 별 개수를 담기 위한 dictionary
        Dictionary<int, int> dic = new Dictionary<int, int>();

        foreach (int size in tangerine)
        {
            if(dic.ContainsKey(size))
                dic[size]++;
            else
                dic[size] = 1;
        }

        // 내림차순으로 정리
        List<int> list = dic.Values.OrderByDescending(x => x).ToList();

        int answer = 0;
        int count = 0;
        foreach (int i in list)
        {
            count += i;
            answer++;

            if (count >= k)
                break;

        }

        // 1 22 33 4 55

        return answer;
    }


    public static void Main(string[] args)
    {

        Solution s = new Solution();

        s.solution(6, new int[] { 1, 3, 2, 5, 4, 5, 2, 3 });

        Console.WriteLine(s.solution(6, new int[] { 1, 3, 2, 5, 4, 5, 2, 3 }));
    }
}

 

dictionary로 각 귤의 개수를 카운팅 해주고, 이를 dic.Values.OrderByDescending() Linq함수로 key값을 무시한 value만을 내림차순list로 정렬해준다.

 

그리고 list를 foreach문으로 돌리면서 k만큼 카운팅을 해준 값을 return 해준다.