[백준] 2108번 - 최빈값, 값의범위, 중간값

팥빵·2025년 11월 19일

Baekjoon

목록 보기
48/49

>>문제 바로가기<<

주어진 값들의 평균, 중간값, 최빈값, 값의범위를 묻는 문제이다.

한 문제에 뭘 많이도 물어보는구나.. 싶지만 그만큼 얻어갈 것도 많다는 의미이다.

평균은 구하기 쉬우니 나머지를 구하는 방법을 알아보자.


1. 중간값

Scanner sc = new Scanner(System.in);

int N = sc.nextInt();
int[] arr = new int[N];

for(int i=0; i<N; i++){
	arr[i] = sc.nextInt();
}

Arrays.sort(arr);
int mid = arr[N / 2];

배열에 값들을 모두 저장한 후

Arrays.sort();

해당 메소드로 오름차순 정렬로 쉽게 구할 수 있다.
정수 N은 홀수로 입력 받아지고, 배열은 0부터 N-1번까지 값이 저장되기 때문에
N/2번째 값이 중간값이 된다.


2. 최빈값

Scanner sc = new Scanner(System.in);

int N = sc.nextInt();
Map<Integer, Integer> map = new HashMap<>();

for(int i=0; i<N; i++){
	int num = sc.nextInt();
	map.put(num, getOrDefault(num, 0) + 1);
}

int maxValue = Collections.max(map.values());
List<Integer> list = new ArrayList<>();

for(int key : map.keySet()){
	if(map.get(key) == maxValue){
    	list.add(key);
    }
}

Collections.sort(list);
int max = (list.size() == 1) ? list.get(0) : list.get(1);

문제에서 요구하는 출력은
가장 많이 입력된 값을 출력하고,
만약 그러한 값이 2개 이상이면
두번째로 적게 입력된 값을 출력하라고 되어있다.

때문에 가장 많이 입력된 값을 maxValue변수로 지정해놓고
이와 동일한 빈도로 나온 값들을 list로 모아 오름차순 정렬을 한 다음에

list의 크기가 1이면 최빈값이 유일하단 의미이므로 그대로 출력,
만약 그렇지 않으면 2번째 값(list.get(1)) 을 출력하면 된다.

위와 같은 절차에 필요한 메소드는 다음과 같다.

getOrDefault(num, 0);
// Key:num에 대한 값이 존재하면 Value값을 반환, 없으면 0을 반환

Collections.sort();
// 콜렉션 자료구조들의 오름차순 정렬

Collections.max(map.values());
// 콜렉션 자료구조 요소의 value값 중 최댓값을 반환


3. 값의 범위

Scanner sc = new Scanner(System.in);

int N = sc.nextInt();
int[] arr = new int[N];

for(int i=0; i<N; i++){
	num = sc.nextInt();
	arr[i] = num;
}

Arrays.sort(arr);
int range = arr[N-1] - arr[0];

따로 maxmin으로써 변수를 만들어 비교하는 것 대신
배열을 오름차순 정렬하고, 맨 끝과 맨 처음값을 빼주면 된다.


위 정보를 바탕으로 설계한 코드는 다음과 같다.

import java.util.*;
import java.io.*;

class Main{
	public static void main(String[] args) throws IOException{
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int N = Integer.parseInt(br.readLine());
        int[] arr = new int[N];
        int sum = 0;
        
        Map<Integer, Integer> map = new HashMap<>();
        
        for(int i=0; i<N; i++){
        	int num = Integer.parseInt(br.readLine());
            arr[i] = num;
            sum += num;
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        
        int avg = (int)Math.round((double)sum / N);
        
        Arrays.sort(arr);
        int mid = arr[N/2];
        int range = arr[N-1] - arr[0];
        
        int maxValue = Collections.max(map.values());
        List<Integer> list = new ArrayList<>();
        
        for(int key : map.keySet()){
        	if(map.get(key) == maxValue){
            	list.add(key);
            }
        }
        
        Collections.sort(list);
        int max = (list.size() == 1) ? list.get(0) : list.get(1);
        
        bw.write(avg + "\n");
        bw.write(mid + "\n");
        bw.write(max + "\n");
        bw.write(range + "\n");
        
        bw.flush();
        bw.close();
    }
}

맞았습니다!!

profile
반갑습니다

0개의 댓글