주녘공부일지

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

Programmers - C#/CodingTest Lv.2

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

주녘 2023. 8. 25. 17:39
728x90

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

- 크기별로 귤의 개수를 카운트 -> 많은 개수부터 체크

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

    public class Solution
    {
        public int solution(int k, int[] tangerine)
        {
            Dictionary<int, int> dict = new Dictionary<int, int>();

            int answer = 0;

            // 귤 크기에 따라 딕셔너리에 담아 갯수파악
            for (int i = 0; i < tangerine.Length; i++)
            {
                if (!dict.ContainsKey(tangerine[i]))
                    dict.Add(tangerine[i], 1);
                else
                    dict[tangerine[i]]++;
            }

            // 딕셔너리의 값을 내림차순 정렬해서 List로 담음
            var sortList = dict.OrderByDescending(x => x.Value).ToList();
            int sum = 0;

            // 가장 많은 수의 귤부터 먼저 넣어서 체크
            for (int i = 0; i < sortList.Count; i++)
            {
                answer++;
                sum += sortList[i].Value;
                if (sum >= k)
                    break;
            }

            return answer;
        }
    }
728x90