数组中出现次数超过一半的数字
一:
function MoreThanHalfNum_Solution(numbers)
{
var obj = {};
var length = numbers.length;
numbers.forEach(function(d) {
if (obj[d]) {
obj[d]++;
} else {
obj[d] = 1;
}
})
for (var i in obj) {
if (obj[i] > Math.floor(length / 2)) {
return i;
}
}
return 0;
}
二:
function MoreThanHalfNum(arr) {
arr.sort();
if(arr.length%2===0){
console.log(arr[arr.length/2])
}else {
console.log(arr[(arr.length-1)/2])
}
}
var arr=[0,1,2,3,3,3,3];
MoreThanHalfNum(arr); //3