Algorithms
Migratory Birds
seoca
2020. 10. 1. 23:50
The solution in Javascript I (Failed in HackerRank)
sort 를 이용. 순서대로 정렬해준 후에 동일한 값의 (last index - first index) + 1 (0부터 시작하니까)
해외 블로그 접근이 좋긴했지만 결과적으로 HackerRank에서는 fail.
const arr = [1, 2, 3, 4, 5, 4, 3, 2, 1, 3, 4, 1]
function migratoryBirds(arr) {
let bird = 1;
let max = bird; //bird 의 시작이 1이라는 것은 at least one bird id는 존재한다는 의미. 나중에 더 큰 값이오면 대체.
let result = 0;
arr.sort(); //1,1,1,2,2,3,3,3,4,4,4,5
for (let i = 0; i < arr.length; i++) {
//lastIndexOf: 해당 value가 가장 마지막으로 발견된 index return.
bird = (arr.lastIndexOf(arr[i]) - arr.indexOf(arr[i])) + 1; //index 넘버인데 왜 1을 더하지? -> indexOf가 0부터 시작하니까 total count를 위해서 +1
if (bird > max) { //**important**가장 많은 id를 차지하는 bird를 찾을때 까지만! 같은게 아니라 무조건 커야지 해당되기에 동일 한 count면 더 큰 수로 옮겨가지를 않는다.
max = bird; //가장 많은 id를 차지하는 bird count로 대체 됨.
result = arr[i];
}
}
console.log(result); //1
}
migratoryBirds(arr);
The solution in Javascript II
Reference
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