JavaScript 陣列中的四分之一元素
問題
JavaScript 函式接收一個整數陣列,該陣列按遞增順序排序,arr。
陣列中有一個整數出現的次數超過四分之一 (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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP