一、题目链接
https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
二、具体代码
/**
* @param {number[]} nums
* @return {number}
*/
// 摩尔投票法
// 时间复杂度:O(n)
// 空间复杂度:O(1)
var majorityElement = function(nums) {
let x = 0, votes = 0, count = 0;
// 1、摩尔投票法核心代码
for(let num of nums) {
if(votes === 0) {
x = num;
}
votes += x === num ? 1 : -1;
}
// 2、判断x是否是数组中出现长度超过一半的数,是的话,直接返回,不是的话,返回0
for(let num of nums) {
if(x === num) {
count++;
}
}
return count > nums.length / 2 ? x : 0;
};