【leetcode】169. 多数元素

82 阅读1分钟

leetcode-169.png

这一题也是比较简单的一题,但是题目有限制,如果没有限制的话,做法还是比较多的。
可以先排序,然后再返回中间的元素即可。

var majorityElement = function (nums) {
    nums.sort((a, b) => a - b)
    return nums[Math.floor(nums.length / 2)]
};

题目进阶版要求在线性时间内解决。

摩尔投票法

下面这段代码的逻辑比较好理解,对于候选者的计数随时进行加减,如果 cnt === 0,那么就换一个候选

var majorityElement = function (nums) {
    let candidate = null
    let cnt = 0
    for (let num of nums) {
        if (cnt === 0) {
            candidate = num
            cnt++
        } else if (num === candidate) {
            cnt++
        } else {
            cnt--
        }
    }
    return candidate
};