[백준] 2108 통계학
https://www.acmicpc.net/problem/2108
2108번: 통계학
첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4,000을 넘지 않는다.
www.acmicpc.net
이 문제는 정렬 카테고리에 있는 내가 문제를 잘못푼건지 솔직히 왜 정렬로 분류되었는 지는 잘 모르겠다. 중간중간에 배열이나 리스트 같은걸 정렬해서 그런 것 같기도 하다.
요구조건이 상세하게 명시되어 있는 편이라 그렇게 어려운 편의 문제는 아니었다.
문제 및 입출력
테스트 케이스
코드
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// 예외처리 : 숫자 1개만 입력했을 경우
if(n==1)
{
int print = sc.nextInt();
for(int i=0; i<3; i++)
{
System.out.println(print);
}
// 범위는 무조건 0으로 출력
System.out.println(0);
return;
}
int[] arr = new int[n];
int[] cnt = new int[4000*2+1];
double sansul = 0.0;
for(int i=0; i<n; i++)
{
arr[i] = sc.nextInt();
sansul += arr[i]; // 산술평균 구하기
cnt[arr[i]+4000]++; // 최빈값 구하기
}
// 1. 산술평균
System.out.println((int)Math.round((double)(sansul/n)));
// 2. 중앙값
Arrays.sort(arr);
System.out.println(arr[n/2]);
// 3. 최빈값
int max = Integer.MIN_VALUE;
ArrayList<Integer> index = new ArrayList<Integer>();
for(int i=0; i<cnt.length; i++)
{
max = Math.max(max, cnt[i]);
}
for(int i=0; i<cnt.length; i++)
{
if(max==cnt[i])
{
index.add(i);
}
}
if(index.size()==1) // 3-1. 최빈값이 하나만 있을 경우, 리스트에는 값 1개
{
System.out.println(index.get(0)-4000);
}
else // 3-2. 최빈값이 여러 개 있을 경우, 오름차순 정렬한 후 2번째 값 출력
{
Collections.sort(index);
System.out.println(index.get(1)-4000);
}
// 4. 범위
System.out.println(Math.abs(arr[arr.length-1]-arr[0]));
sc.close();
}
}