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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短