728x90
https://www.hackerrank.com/challenges/migratory-birds/problem
Migratory Birds | HackerRank
Determine which type of bird in a flock occurs at the highest frequency.
www.hackerrank.com
Algorithms > Implementation
주어진 배열에서 가장 자주 등장하는 id값을 출력한다.
단, 같은 빈도의 id가 여러 개일 경우 더 작은 값을 출력한다.
코드
int migratoryBirds(int arr_count, int* arr) {
int *check = (int *)malloc(arr_count * sizeof(int));
for (int i = 0; i < arr_count; i++) check[i] = 0; // check 배열 초기화
for (int i = 0; i < arr_count; i++) check[arr[i]]++;
int res = 0, res_idx = 0; // res: 가장 많이 등장한 수, res_idx: 가장 많이 등장한 수의 id(index)
for (int i = 0; i < arr_count; i++)
if (check[i] > res){
res = check[i];
res_idx = i;
}
return res_idx;
}
설명
동적 배열 check를 선언한다.
for문을 이용해 check 배열의 arr_count번 인덱스까지의 값을 0으로 초기화하고 시작한다.
다른 for문을 이용해 arr[i]의 값을 인덱스로 하는 check 배열의 값을 1 증가시킨다.
즉, arr[i]가 3이면 check[3]의 값을 증가시키면서 해당 값이 얼마나 나왔는지 체크한다.
체크가 끝나면 다른 for 루프에서 가장 많이 등장한 수와 그 수의 id값(check배열에서의 인덱스)을 찾는다.
모든 과정 이후 res_idx를 리턴한다.
728x90
'C & C++ > HackerRank' 카테고리의 다른 글
[HackerRank] Breaking the Records (1) | 2021.09.19 |
---|---|
[HackerRank] Running Time of Algorithms (0) | 2021.09.19 |
[HackerRank] The Power Sum (0) | 2021.09.09 |
[HackerRank] Staircase (0) | 2021.08.29 |
[HackerRank] Quicksort 1 - Partition (0) | 2021.08.29 |