题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
选举法,重复次数超过整个数组长度一半的元素,最后的count肯定为1及以上
function MoreThanHalfNum_Solution(numbers)
{
// write code here
if( numbers.length === 1) return numbers[0];
let count = 0;
let cur = 0;
for(let i = 0;i<numbers.length;i++){
if(count == 0 ) cur = numbers[i];
if(numbers[i] == cur){
count ++;
}else{
count--;
}
}
return cur;
}