这个数组是否包含任何元素 - Javascript
给定一个数字数组,任何数组元素将是该数组中出现次数超过数组长度一半的多数元素。
例如 -
如果数组长度是 7,
那么,如果数组中出现任意元素 4 次或更多次,它将被视为多数。显然任何特定数组最多只能有一个多数元素。
我们需要写一个 JavaScript 函数,它以一个具有重复值数字数组,如果数组中存在多数元素,则返回 true。如果数组中不存在这样的元素,我们的函数应该返回 false。
示例
以下是代码 -
const arr = [12, 5, 67, 12, 4, 12, 4, 12, 6, 12, 12];
const isMajority = 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];
}else{
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(isMajority(arr));输出
会在控制台产生以下输出 -
true
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP