알고리즘 풀이/백준

[백준][Java] 2108번 통계학

배게 2018. 5. 3. 05:35
728x90

통계학 이전 문제인

'수 정렬하기3' 의 코드인 카운팅정렬 코드를 응용하여 문제를 해결하였습니다.

문제에서 요구하는 4가지 값들이 있는데


첫번째 산술평균은 그냥 숫자들 다 받고 N으로 나누어 Math.round 안에 넣어주시면되고

두번째 중앙값은 정렬한 숫자들인 result배열의 중간값인 (N은 홀수이므로) result[result.length/2]

를 출력해줍니다.

네번째 범위 또한 정렬된 숫자의 끝번째와 첫번째 값을 뺀 값을 출력시킵니다


제일 어려웠던 것이 세번째 최빈값이었는데

문제가 애초에 '수 정렬하기3' 문제와 다르게 음수까지 숫자의 범위가 늘어났기 때문에

기존의 코드를 수정해야 했습니다. 음수까지 포함했으므로

countArr[0]는 -4000의 갯수로, count[8000]은 4000의 갯수로 처리를 해주어

문제를 해결했습니다.

가장 많이 나타나는 값의 개수를 따로 저장하여

for문을 0부터 한번 더 돌려서 2번째로 그 값이 나타나는 경우의 값을

출력하였습니다.



 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.io.*;
import java.nio.Buffer;
import java.util.*;

public class Main {
	
	int[] numbers;
	int[] countArr;
	int[] result;
	
	int max = 0;
	int index = 0;
	BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	void inputNumbers() throws IOException{
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int size = Integer.parseInt(br.readLine().trim());
		numbers = new int[size];
		for(int i=0; i<numbers.length; i++) {
			int num = Integer.parseInt(br.readLine().trim());
			numbers[i] = num;
			if (max < num) max = num;
		}
	}
	
	void sort() throws IOException{
		inputNumbers();
		int maxNumber = max;
		countArr = new int[8001];
		result = new int[numbers.length];
		
		int sum=0;
		int max_count=0, mode=0;
		
		for (int i=0; i<numbers.length; i++) {
			countArr[numbers[i]+4000]++;
		}
		
		for (int i=0; i<countArr.length; i++) {
			if( max_count<countArr[i]) max_count=countArr[i];
		}
		int count=0;
		for (int i=0; i<countArr.length; i++) {
			if( countArr[i]==max_count) {
				count++;
				mode=i-4000;
			}
			if(count==2) break;
		}
		
		
		for (int i=1; i<countArr.length; i++) {
			countArr[i]+=countArr[i-1];
		}
		
		for (int i=numbers.length-1; i>=0; i--) {
			result[--countArr[numbers[i]+4000]] = numbers[i];
			sum+=numbers[i];
		}
		
		
		System.out.println(Math.round((double)sum/result.length));
		System.out.println(result[result.length/2]);
		
		System.out.println(mode);
		System.out.println(result[result.length-1]-result[0]);
		
		bw.close();
		
		
	}
	
	public static void main(String[] args) throws IOException {
		new Main().sort();
		
	}
}