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 해준다.
'백준 등 알고리즘' 카테고리의 다른 글
[C#] 프로그래머스 LV.2 타겟 넘버 (DFS) (0) | 2024.11.23 |
---|---|
[C#] 프로그래머스 Lv.2 프로세스 (Queue 튜플) (0) | 2024.11.22 |
[C#] 프로그래머스 영어 끝말잇기 (1) | 2024.11.17 |
[C#] 백준 14929 귀찮아 (SIB) (3) | 2024.11.15 |
[C#] 백준 18222 투에-모스 문자열 (0) | 2024.11.14 |