1. 문제

2108번: 통계학



2. 개요

홀수인 N개의 수가 주어졌을 때, 이 수들의 산술평균, 중앙값, 최빈값, 범위를 구하여 출력하는 문제.



3. 풀이 및 코드

3-1. 풀이

산술평균, 중앙값, 범위는 어렵지 않게 구할 수 있다.

최빈값의 경우 가장 많이 나온 수가 여러개일 때 두 번째로 작은 수를 출력해줘야 하기 때문에 이만 잘 처리하면 된다.

수의 등장 횟수를 저장할 배열을 만들고 수가 나올때마다 1씩 카운팅해준다. 이 중 가장 큰 수를 최대 등장 횟수로 저장해둔다.

최빈값이 여러개일 경우 두 번째로 작은 값을 구해야하므로 카운트를 2로 잡고 모든 범위 내를 탐색하면서 최대 등장 횟수와 동일하게 등장한 수가 있다면 이를 최빈값으로 갱신하고 카운트를 1씩 줄여준다. 카운트가 0이 되지 않았다면 계속 진행하고 0이 되었다면 탈출한다.

4가지 값을 출력한다.

3-2. Python

import sys

N = int(sys.stdin.readline())

nums = []
count = [0 for i in range(8001)]
maxcount = 0

for i in range(N):
    num = int(sys.stdin.readline())
    nums.append(num)
    
    count[num + 4000] += 1

    if count[num + 4000] > maxcount:
        maxcount = count[num + 4000]

nums.sort()

cnt = 2

for i in range(8001):
    if count[i] == maxcount:
        mode = i - 4000
        cnt -= 1

        if cnt == 0:
            break

total = sum(nums)
mean = int(total / N + 0.5) if total >= 0 else int(total / N - 0.5)

print(mean)
print(nums[N // 2])
print(mode)
print(nums[-1] - nums[0])

3-3. C#

namespace boj_2108
{
    internal class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());

            int N = int.Parse(sr.ReadLine());

            int maxcount = 0;
            List<int> nums = new List<int>();
            int[] count = new int[8001];

            for (int i = 0; i < N; i++)
            {
                int num = int.Parse(sr.ReadLine());
                nums.Add(num);

                count[num +  4000]++;

                if (count[num + 4000] > maxcount)
                    maxcount = count[num + 4000];
            }

            nums.Sort();

            int cnt = 2;
            int mode = 9999;

            for (int i = 0; i < 8001; i++)
            {
                if (count[i] == maxcount)
                {
                    mode = i - 4000;
                    cnt--;
                }

                if (cnt == 0)
                    break;
            }

            int total = nums.Sum();
            int mean = total >= 0 ? (int)(total / (float)N + 0.5) : (int)(total / (float)N - 0.5);

            sw.WriteLine(mean);
            sw.WriteLine(nums[N / 2]);
            sw.WriteLine(mode);
            sw.WriteLine(nums[^1] - nums[0]);
            sw.Close();
        }
    }
}

Comments