{
// write code here
//reduce() 方法接收一个函数作为累加器
let result = numbers.reduce((temp,data) => {
temp[data] = temp[data] ? temp[data] + 1 : 1;
return temp;
},{})
let num;
for(let index in result){
if(result[index] > numbers.length/2){
num = index;
}
}
return num;
}
module.exports = {
MoreThanHalfNum_Solution : MoreThanHalfNum_Solution
};
//排序解法
function MoreThanHalfNum_Solution(numbers)
{
numbers = numbers.sort((a,b) => a-b);
let middle = numbers[Math.floor(numbers.length / 2)];
let count = 0;
numbers.forEach(value => {
if(value === middle){
count++;
}
})
return (count > numbers.length / 2) ? middle : 0;
}
module.exports = {
MoreThanHalfNum_Solution : MoreThanHalfNum_Solution
};
// 对象解法
function MoreThanHalfNum_Solution(numbers)
{
let len = Math.floor(numbers.length / 2);
let obj = {};
for(let i = 0; i < numbers.length; i++){
if(obj[numbers[i]]){
obj[numbers[i]]++;
}else{
obj[numbers[i]] = 1;
}
}
for(let k in obj){
if(obj[k] > len){
return k;
}
}
return 0;
}
module.exports = {
MoreThanHalfNum_Solution : MoreThanHalfNum_Solution
};