समस्या
जावास्क्रिप्ट फ़ंक्शन जो बढ़ते क्रम में क्रमबद्ध पूर्णांकों की एक सरणी लेता है, गिरफ्तार।
सरणी में ठीक एक पूर्णांक है जो एक चौथाई (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