https://www.acmicpc.net/problem/2108
2108번: 통계학
첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4,000을 넘지 않는다.
www.acmicpc.net
계수 정렬을 이용해 정렬하고 문제를 풀었는데 음수 index 및 자료형을 처리하는게 까다로웠다.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
double sum=0;
for(int i=0; i<n; i++){
a[i] = Integer.parseInt(br.readLine());
sum+=(double)a[i];
}
br.close();
long avg = Math.round(sum/(double)n);
int mid;
int count=0;
int r;
int[] range = new int[8001];
int tidx = 0;
for(int i=0; i<n; i++) {
tidx = a[i]+4000;
range[tidx]++;
}
int max = -1;
for(int i=1; i<range.length; i++) {
if(max<range[i]) {
max = range[i];
}
}
for(int i=1; i<range.length; i++) {
range[i] +=range[i-1];
}
int[] ans = new int[n];
for(int i=0; i<n; i++) {
tidx = a[i]+4000;
ans[--range[tidx]] = a[i];
}
HashMap<Integer, Integer> time = new HashMap<>();
int tmax = -1;
for(int i=0; i<n; i++) {
if(time.get(ans[i])==null) {
time.put(ans[i], 1);
}
else time.put(ans[i], time.get(ans[i])+1);
if(time.get(ans[i])>tmax) tmax = time.get(ans[i]);
}
ArrayList<Integer> temp = new ArrayList<>();
for(int i=0; i<n; i++) {
if(time.get(ans[i])==tmax) {
if(!temp.contains(ans[i])) temp.add(ans[i]);
}
}
if(temp.size()==1) {
count = temp.get(0);
}
else count = temp.get(1);
mid = ans[n/2];
int min = ans[0];
int maxs = ans[ans.length-1];
r = maxs-min;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write(avg+"\n");
bw.write(mid+"\n");
bw.write(count+"\n");
bw.write(r+"\n");
bw.close();
}
}
'백준' 카테고리의 다른 글
백준 정렬 - 11651번 : 좌표 정렬하기 2 (0) | 2022.02.09 |
---|---|
백준 정렬 - 11650번 : 좌표 정렬하기 (0) | 2022.02.09 |
백준 정렬 - 10989번 : 수 정렬하기 3 (0) | 2022.02.08 |
백준 번외 - 11506번 : 占쏙옙 (0) | 2022.02.08 |
백준 정렬 - 2751번 : 수 정렬하기 (0) | 2022.02.08 |