Skip to content

169. 多数元素 #68

@Geekhyt

Description

@Geekhyt

原题链接

摩尔投票算法

摩尔投票算法有点“天天爱消除”的感觉,证明过程详见官方题解。

先明确,所谓多数元素就是该元素的个数超过数组长度的一半。

所以我们可以让不同的数字相互抵消,最后剩下的数字就是多数元素。

const majorityElement = function(nums) {
    let target = 0
    let count = 0
    for (let i = 0; i < nums.length; i++) {
        if (count === 0) {
            target = nums[i]
        }
        if (nums[i] === target) {
            count++
        } else {
            count--
        }
    }
    return target
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy