최빈값 구하기

주어진 int 배열 값 중에서 자주 나오는 값을 반환하면 되는데 이때 최빈값이 여러 개라면 -1을 반환하면 되는 문제였다.

 

나의 풀이

값들을 담는 frequentDict라는 딕셔너리를 만든 뒤

첫 for문에서 값들을 중복체크하여 딕셔너리에 담고

첫 번째 foreach문에서 max키와 value를 구한다.

두 번째 foreach문에서 최빈값이 여러 개인지 확인해 맞다면 -1을 answer에 대입한다.

Dictionary<int, int> frequentDict = new Dictionary<int, int>();
int answer = 0;

for (int i = 0; i < array.Length; i++)
{
    if (!frequentDict.ContainsKey(array[i]))
    {
        frequentDict.Add(array[i], 1);
    }
    else
    {
        frequentDict[array[i]]++;
    }
}
int max = 0;
foreach (var item in frequentDict)
{
    if (item.Value > max)
    {
        max = item.Value;
        answer = item.Key;
    }
}


foreach (var item in frequentDict)
{
    if (answer != item.Key && max == item.Value)
    {
        answer = -1;
        break;
    }
}

return answer;

 

다른 사람의 풀이

array를 n으로 그룹화하여 g.Count()를 사용해 대응되는 개수를 지정하였다.

이후 list의 cnt 기준으로 Max()를 이용하여 max인 것을 찾아 max에 넣는다.

max가 2개 이상이면 answer에 -1을 대입하고 아니면 첫번째의 n(키값)을 대입한다.

짧은 구문이지만 꽤나 이해하기 어려운 것 같다. 다시 복습해보자.

var list = array.GroupBy(x => x, g => g, (x, g) => new { n = x, cnt = g.Count() });
var max = list.Where(x => x.cnt == list.Max(o => o.cnt));
int answer = max.Count() == 1 ? max.First().n : -1;

 

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

 

프로그래머스

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

programmers.co.kr

 

+ Recent posts