문제
오름차순으로 정렬된 정수 배열을 취하는 JavaScript 함수, arr.
배열에 4분의 1(25%) 이상 발생하는 정수가 정확히 하나 있습니다. 함수는 해당 숫자를 반환해야 합니다.
예를 들어, 함수에 대한 입력이 -
인 경우const arr = [3, 5, 5, 7, 7, 7, 7, 8, 9];
그러면 출력은 다음과 같아야 합니다. -
const output = 7;
예시
이에 대한 코드는 -
const arr = [3, 5, 5, 7, 7, 7, 7, 8, 9];
const oneFourthElement = (arr = []) => {
const len = arr.length / 4;
const search = (left, right, target, direction = 'left') => {
let index = -1
while (left <= right) {
const middle = Math.floor(left + (right - left) / 2);
if(arr[middle] === target){
index = middle;
if(direction === 'left'){
right = middle - 1;
}else{
left = middle + 1;
};
}else if(arr[middle] < target){
left = middle + 1;
}else{
right = middle - 1;
};
};
return index;
};
for(let i = 1; i <= 3; i++){
const index = Math.floor(len * i);
const num = arr[index];
const loIndex = search(0, index, num, 'left');
const hiIndex = search(index, arr.length - 1, num, 'right');
if(hiIndex - loIndex + 1 > len){
return num;
};
};
};
console.log(oneFourthElement(arr)); 출력
콘솔의 출력은 -
7