[JAVA] SWEA (D2) 1204. 최빈수 구하기

AIR·2023년 10월 22일
0

링크

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=2&contestProbId=AV13zo1KAAACFAYh&categoryId=AV13zo1KAAACFAYh&categoryType=CODE&problemTitle=&orderBy=INQUERY_COUNT&selectCodeLang=JAVA&select-1=2&pageSize=10&pageIndex=1


문제 설명

(정답률 53.05%)
최빈수를 출력하는 프로그램을 작성하여라 (단, 최빈수가 여러 개 일 때에는 가장 큰 점수를 출력하라).


나의 코드

  1. 주어진 입력값을 배열로 받는다.
  2. HashMap을 이용해 배열의 원소를 key, 개수를 value로 받는다.
  3. value가 제일 클 때의 key를 출력한다.
import java.io.*;
import java.util.*;

class SWEA {
    public static void main(String[] args) throws IOException {

        System.setIn(new FileInputStream("src/input.txt"));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int T = Integer.parseInt(br.readLine());
        HashMap<Integer, Integer> map;
        
        for (int test_case = 1; test_case <= T; test_case++) {

            int t = Integer.parseInt(br.readLine());
            map = new HashMap<>();
            //student 배열 생성
            String[] student = br.readLine().split(" ");

            for (String s : student) {
                int n = Integer.parseInt(s);
                int cnt = 1;
                //맵에 n이 포함될 경우 카운트해서 map에 다시 추가
                if (map.containsKey(n)) {
                    cnt = map.get(n);
                    map.put(n, ++cnt);
                } else {
                    map.put(n, cnt);
                }
            }
            
            int maxCount = 0;	//최대 개수를 담을 변수
            int answer = 0;
            for (Integer i : map.keySet()) {
                if (maxCount <= map.get(i)) {
                    maxCount = map.get(i);
                    answer = i;
                }
            }

            System.out.println("#" + t + " " + answer);
        }
    }
}

정리

나는 학생들의 점수를 받을 배열과 빈도 수를 카운트하기 위해 HashMap을 사용하였는데
다음과 같이 배열만 써서 카운트할 수 있었다.

int[] scores = new int[101]; //각 점수를 카운트할 배열
for (int i = 0; i < 1000; i++) { //1000명의 학생의 점수 입력
	scores[sc.nextInt()]++;
}
profile
백엔드

0개의 댓글