(정답률 53.05%)
최빈수를 출력하는 프로그램을 작성하여라 (단, 최빈수가 여러 개 일 때에는 가장 큰 점수를 출력하라).
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()]++;
}