JavaScript 確定擁有多數元素的陣列,如果它在同一個陣列中,則返回 TRUE
我們需要編寫一個 JavaScript 函式,該函式接收一個具有重複值的數字陣列,並返回出現次數超過 (n/2) 的數字,其中 n 是陣列的長度。如果陣列中沒有此類元素,則我們的函式應返回 false
讓我們編寫此函式的程式碼 −
示例
const arr = [12, 5, 67, 12, 4, 12, 4, 12, 6, 12, 12];
const arr1 = [3, 565, 7, 23, 87, 23, 3, 65, 1, 3, 6, 7];
const findMajority = arr => {
let maxChar = -Infinity, maxCount = 1;
// this loop determines the possible candidates for majorityElement
for(let i = 0; i < arr.length; i++){
if(maxChar !== arr[i]){
if(maxCount === 1){
maxChar = arr[i];
} 0else {
maxCount--;
};
} else {
maxCount++;
};
};
// this loop actually checks for the candidate to be the majority
element
const count = arr.reduce((acc, val) => maxChar===val ? ++acc : acc, 0);
return count > arr.length / 2;
};
console.log(findMajority(arr));
console.log(findMajority(arr1));輸出
控制檯中的輸出為 −
true false
廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP