1 minute read

Migratory Birds (Hacker Rank)

A flock of birds is flying across the continent. Each bird has a type, and the different types are designated by the ID numbers , , , , and .

Given an array of integers where each integer describes the type of a bird in the flock, find and print the type number of the most common bird. If two or more types of birds are equally common, choose the type with the smallest ID number.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int migratoryBirds(int n, int[] ar) {
        int[] type = new int[5];
        for(int i = 0; i < n; i++){
            int idx = ar[i]-1;
            type[idx]++;
        }
        int max = type[0];
        int num = 1;
        for(int i = 0; i < 5; i++){
            if(max < type[i]){
                max = type[i];
                num = i+1;
            }
            if(max == type[i]){
                if(num > i+1){
                    num = i+1;
                }
            }
        }
        return num;

    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] ar = new int[n];
        for(int ar_i = 0; ar_i < n; ar_i++){
            ar[ar_i] = in.nextInt();
        }
        int result = migratoryBirds(n, ar);
        System.out.println(result);
    }
}

행운의 77문제 프로젝트
  행운의 77문제 프로젝트는 한 달동안 알고리즘 문제 77개를 푸는 프로젝트입니다.