HR - Migratory Birds

Goody·2021년 2월 4일
0

알고리즘

목록 보기
27/122

문제

Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.

  • Example
    arr = [1,1,2,2,3]
    There are two each of types 1 and 2, and one sighting of type 3. Pick the lower of the two types seen twice: type 1.

예시

INPUT

6
1 2 3 4 5 4 3 2 1 3 4

OUTPUT

3

Explanation

The different types of brids occur in the following frequencies:

  • Type 1 : 2
  • Type 2 : 2
  • Type 3 : 3
  • Type 4 : 3
  • Type 5 : 1
    Two types have a frequency of 3 , and the lower of those is type 3.

풀이

  • 배열 내 5 종류의 숫자들 중에서 어떤 수가 가장 많이 들어 있는지 찾아내는 문제이다.
  • 두 id의 빈도 수가 같은 경우에는 id 값이 더 작은 수를 반환한다.
  • 주어진 배열을 돌면서 원소가 id와 일치할 때마다, 미리 준비해 둔 id 카운트 배열의 원소를 증가시킨다.
  • id 카운트 배열 원소들의 값이 다 정해지면, 원소 중 최대값이 가장 높은 빈도수가 된다.
  • 최대값을 갖는 인덱스 중, id 값이 더 작은 수를 찾아야 하므로 indexOf 메서드로 최대값과 일치하는 가장 앞쪽의 원소의 인덱스를 구한다.

코드

function migratoryBirds(arr) {
    let birds = [0, 0, 0, 0, 0];

    arr.forEach((e) => {
        if(e === 1) birds[0]++;
        if(e === 2) birds[1]++;
        if(e === 3) birds[2]++;
        if(e === 4) birds[3]++;
        if(e === 5) birds[4]++;
    });

    const max = birds.reduce((a,b) => Math.max(a,b));
    const maxBirdId = birds.indexOf(max) + 1;
    return maxBirdId;
}

0개의 댓글