SWEA 1204 (S/W 문제해결 기본) 1일차 - 최빈수 구하기

1 개요[ | ]

SWEA 1204 (S/W 문제해결 기본) 1일차 - 최빈수 구하기

2 C++[ | ]

#include<iostream>
 
using namespace std;
 
int main() {
    int T, test, n;
     
    cin >> T;
 
    for (test = 1; test <= T; test++) {
        cin >> n;
        
        int check[101] = { 0 }, max = 0, index;
        for (int i = 0; i < 1000; i++) {
            int N;
            cin >> N;
            check[N]++;
        }
 
        for (int i = 100; i > -1; i--) {
            if (max < check[i]) {
                max = check[i];
                index = i;
            }
 
        }
 
        cout << '#' << test << ' ' << index << '\n';
         
    }
    return 0;
}

3 Java[ | ]

import java.util.*;
public class Solution {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int T, x, xx;
        T = sc.nextInt();
        
        int[] counts;
        int max_count, i, num, max_num;
        for(xx=0; xx<T; xx++) {
            x = sc.nextInt();
            counts = new int[101];
            max_count = 0;
            for(i=0; i<1000; i++) {
                num = sc.nextInt();
                counts[num]++;
                if( counts[num] > max_count ) max_count = counts[num];
            }
            max_num = -1;
            for(i=0; i<101; i++) {
                if( counts[i] != max_count ) continue;
                max_num = i;    
            }
            System.out.format("#%d %d\n", x, max_num);
        }
    }
}

4 Python[ | ]

  • 1. 우리가 알고싶은 최빈수 값(mode) 변수를 만든다.
  • 2. 최빈수 딕셔너리(dictionary)를 만든다. ex) 8이 2개, 4가 3개일 경우 {8:2, 4:3}
  • 3. 최빈수 딕셔너리를 숫자값(key)과 카운트값(value)을 items()로 꺼내와 for문을 돌린다.
  • 4. 카운트값(value)이 최댓값(즉, 최빈수)일때 최빈수값(mode)에 숫자값(key)을 넣는다.
  • 5. 꺼낸 카운트값이 최댓값과 같을 경우 숫자값을 비교하여 큰 숫자를 넣는다.
  • 6. 최빈수 값(mode)을 출력한다.
T = int(input())
for i in range(T):
    test_number = int(input())
    scores = list(map(int, input().split()))
    mode = 0  # 1

    # 2
    count_dic = {}
    for i in scores:
        if i in count_dic:
            count_dic[i] += 1
        else:
            count_dic[i] = 1
    # 3
    max_count = 0
    for key, value in count_dic.items():
        if max_count < value:  # 4
            max_count = value
            mode = key
        elif max_count == value:  # 5
            if mode < key:
                mode = key
    # 6
    print('#{} {}'.format(test_number, mode))

5 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}