39. 数组中出现次数超过一半的数字

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

限制:
1 <= 数组长度 <= 50000

注意:本题与主站 169 题相同:https://leetcode-cn.com/problems/majority-element/

排序后的中间索引

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        return nums[len(nums) // 2]

字典

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        d = {}
        count = len(nums) // 2
        for i in nums:
            if i not in d:
                d[i] = 1
            else:
                d[i] += 1
        for i in d:
            if d[i] > count:
                return i

摩尔根投票。由于众数出现的次数超过数组长度的一半;若记 众数 的票数为 +1 ,非众数 的票数为 −1 ,遍历结束后结果一定 >0

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        if not nums:
            return
        cand = nums[0]
        count = 0
        for i in nums:
            if count == 0:
                cand = i
                count = 1
                continue
            if cand == i:
                count += 1
                continue
            if cand != i:
                count -= 1
                continue
        return cand
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。