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