你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
var majorityElement = function(arr) {
let obj={};
let res=null;
arr.forEach(function(item,index){
// console.log(item,index)
if(obj[item]==undefined){
obj[item]=1
}else{
obj[item]++
}
})
// console.log(obj)
for(var n in obj){
// console.log(n,obj[n])
if(obj[n]>arr.length/2){
// console.log(obj[n],n)
res=n
}
}
return res
};
该篇博客探讨了一个寻找数组中多数元素的算法问题,给出了一段JavaScript实现的代码。算法通过遍历数组,使用对象存储每个元素出现的次数,然后遍历对象找出出现次数超过数组长度一半的元素作为多数元素。这种方法简洁高效,适用于非空数组并确保多数元素存在的情况。
551

被折叠的 条评论
为什么被折叠?



