169.多数元素|字典|moore投票计数法

在这里插入图片描述

  • 字典记录{数:出现次数}
  • 时间复杂度O(n),空间复杂度O(n)
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        # nlen = len(nums)
        dicts = collections.defaultdict(int) 
        res = []
        for val in nums:
            dicts[val] += 1
            if not res or res[1] < dicts[val]:
                res = [val, dicts[val]] # 记录一对值【标记出现次数最多的数,出现次数】
        return res[0]
  • 投票计数法
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        res = nums[0]
        count = 0
        for val in nums:
            if res == val:
                count += 1 # 计数加一
            else:
                count -= 1 # 票数抵消
                if count == 0:
                    res = val # 开始的res退出擂台,res更新为当前数值
                    count = 1
        # 为什么能行得通呢?因为res的数量-其他数的数量>=1,就算极端情况下,假设‘其他数’都是一个数,他的数量也比res的数量小,能够抵消掉
        # 如果‘其他数’是多个不一样的数,顶多也是res一挑多,武力值还是最高的,而且其他数还可能内部消耗。【PS:主观理解】
        return res

参考链接:Java-3种方法(计数法/排序法/摩尔投票法)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值