본문 바로가기
Swexpert

[SW Expert Academy] Intermediate / Array1 / 1204. [S/W 문제해결 기본] 최빈수 구하기

by 29살아저씨 2021. 8. 12.
반응형

Array1) 1204. 최빈수구하기_

 

package array1;

import java.util.Scanner;
import java.io.FileInputStream;

class Solution {
	public static void main(String args[]) throws Exception {

		// txt 파일 읽어오는 소스코드
		// System.setIn(new FileInputStream("res/input.txt"));

		Scanner sc = new Scanner(System.in);
		int T;
		T = sc.nextInt();
		/*
		 * 여러 개의 테스트 케이스가 주어지므로, 각각을 처리합니다.
		 */
		int N;
		int[] stud = new int[1000]; // 학생 수 1000명 배열 생성
		int[] score = new int[101]; // 0~100점까지 100개의 배열 생성
//		now = 최빈수의 count 값 , max = 현재 최빈수
		int now = 0;
		int max = 0;

//		test_case T만큼 실행
		for (int test_case = 1; test_case <= T; test_case++) {
			N = sc.nextInt();

//			1. 점수 읽어와서 저장
			for (int i = 0, end = stud.length; i < end; i++) {
				stud[i] = sc.nextInt();
				score[stud[i]]++; // 각 점수마다 최빈수 측정을 위한 count++

//			2. count 비교하여 최빈수 업데이트
				if (score[stud[i]] >= now) {
					if (score[stud[i]] == now) { // count가 같을 때 같이 큰 최빈수 저장
						max = (max > stud[i]) ? max : stud[i];
						now = score[stud[i]];
						continue;
					}
					max = stud[i];
					now = score[stud[i]];
				}
			}

//			3. 최빈수 출력 및 초기화
			System.out.printf("#%d %d\n", N, max);
			for (int reset = 0; reset < score.length; reset++) {
				score[reset] = 0;
			}
			max = 0;
			now = 0;
		}
	}
}
반응형

댓글