[Java] SWEA 1204 최빈수 구하기

Lee GaEun·2024년 10월 28일

[Java] 알고리즘

목록 보기
8/93

1204 최빈수 구하기 문제 링크

문제분석

  • 1000명 수학 성적의 최빈수 구하기

제약 사항

  • 학생은 1000명
  • 각 학생의 점수는 0이상 100이하
  • 최빈수가 여러 개 인 경우, 가장 큰 점수를 출력

입력 조건

  • 첫째 줄 : 테스트 케이스 개수 ( T )
  • 둘째 줄 : 테스트 케이스 번호
  • 셋째 줄 : 학생 1000명의 수학 점수
  • 둘째 줄과 셋째 줄의 반복

출력 조건

  • #부호 + 테스트 케이스 번호 + 공백 + 최빈수 출력

#1

  • 성적을 index로 받아와 mode의 해당 값에 +1
  • 만들어진 mode 배열의 값을 비교하여 가장 큰 값의 index가 최빈값
import java.util.Scanner;
import java.io.FileInputStream;

class Solution
{
    public static void main(String args[]) throws Exception
    {
        Scanner sc = new Scanner(System.in);
        int T;
        T=sc.nextInt();

        for(int test_case = 1; test_case <= T; test_case++)
        {
            int N = sc.nextInt();
            int answer = 0;

            int[] mode = new int[101];

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

            for(int i=0; i<101; i++) {
                answer = mode[answer] <= mode[i] ? i : answer;
            }

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

  • 성공!

4/30 다시 풀어봄

7분

#1


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

/*
   사용하는 클래스명이 Solution 이어야 하므로, 가급적 Solution.java 를 사용할 것을 권장합니다.
   이러한 상황에서도 동일하게 java Solution 명령으로 프로그램을 수행해볼 수 있습니다.
 */
class Solution
{
    public static void main(String args[]) throws Exception
    {
        Scanner sc = new Scanner(System.in);
        int T;
        T=sc.nextInt();

        for(int test_case = 1; test_case <= T; test_case++)
        {
            int N = sc.nextInt();
            int[] arr = new int[101];
            for(int i=0; i<1000; i++) {
                arr[sc.nextInt()]++;
            }

            int max = 0;
            for(int i=0; i<101; i++) {
                if(arr[i] >= arr[max]) {
                    max = i;
                }
            }

            System.out.println("#"+test_case+" "+max);
        }
    }
}

  • 성공!
profile
I will give it my all (๑•̀o•́๑)ง

0개의 댓글