[BaekJoon] 2108번 - 통계학 [Java][C++]
[BaekJoon] 2108번 - 통계학 [Java][C++]
1. 문제 풀이
산술평균, 중앙값, 최빈값, 범위를 구하는 문제로 산술평균은 모든 수의 합을 수의 개수로 나누면 되며, 중앙값과 범위는 정렬을 활용하면 간단하게 구할 수 있다. 최빈값은 $1$ 개만 존재할 경우와 여러 개가 존재할 경우만 잘 처리해주면 되며, 최빈값의 개수의 최댓값을 $2$로 고정하고 카운팅 배열의 앞에서부터 최빈값이면 최빈값의 개수를 하나씩 빼서 $0$ 이 되는 순간의 최빈값을 찾는 방식으로 구현했다.
2. 코드
1. 풀이 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.io.*;
import java.util.*;
public class Main {
static final int MAX = 4000;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] arr = new int[N];
int sum = 0;
int[] cntArr = new int[MAX + 1 + MAX];
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(br.readLine());
sum += arr[i];
cntArr[arr[i] + MAX]++;
}
Arrays.sort(arr);
int max = 0; // 최빈값의 최댓값
int cntMax = 0; // 최빈값의 최댓값이 등장한 횟수
for (int cnt : cntArr) {
if (cnt > max) {
max = cnt;
cntMax = 1;
} else if (cnt == max) {
cntMax++;
}
}
cntMax = Math.min(cntMax, 2);
int mode = 0; // 최빈값
for (int i = 0; i < cntArr.length; i++) {
if (cntArr[i] == max) cntMax--;
if (cntMax == 0) {
mode = i - MAX;
break;
}
}
System.out.println(Math.round((double) sum / N));
System.out.println(arr[N / 2]);
System.out.println(mode);
System.out.println(arr[N - 1] - arr[0]);
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <bits/stdc++.h>
using namespace std;
constexpr int MAX = 4000;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
sort(v.begin(), v.end());
int sum = 0;
for (int x : v) sum += x;
vector<int> cntArr(MAX + 1 + MAX);
for (int x : v) cntArr[x + MAX]++;
int mx = 0; // 최빈값의 최댓값
int cntMx = 0; // 최빈값의 최댓값이 등장한 횟수
for (int cnt : cntArr) {
if (cnt > mx) {
mx = cnt;
cntMx = 1;
} else if (cnt == mx) {
cntMx++;
}
}
cntMx = min(cntMx, 2);
int mode = 0; // 최빈값
for (int i = 0; i < cntArr.size(); i++) {
if (cntArr[i] == mx) cntMx--;
if (cntMx == 0) {
mode = i - MAX;
break;
}
}
cout << (int)round((double)sum / n) << '\n';
cout << v[n / 2] << '\n';
cout << mode << '\n';
cout << v[n - 1] - v[0] << '\n';
}
This post is licensed under CC BY 4.0 by the author.