多数元素-数组169-python

没看答案,哈希表法。时间复杂度O(n),空间复杂度O(n)。

from collections import defaultdict

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        n = len(nums)
        count = defaultdict(int)

        for num in nums:
            count[num] += 1
            if count[num] >= n // 2 + 1:
                return num
        
        return -1

摩尔投票法,时间复杂度O(n),空间复杂度O(1):

  • 假设不同数字相互抵消,那么最后剩下的数字,就是我们要找的多数元素。
  • 我们可以把这个过程打个比方,比如现在多军对峙,假设阵营A士兵人数比其他方的人数都多,阵营A士兵能以一杀一,那么只要阵营A士兵不杀自己人(相同数字),去杀不同阵营的人(不同数字),那么最后剩下的那些士兵,就是阵营A的士兵。
  • 因此我们可以假设数组的第一个数字为target,然后遍历数组,我们尝试用计数count模拟这个抵消的过程,规则如下:
    • 当数组中的元素与假设的target不相等时,计数count减1,即模拟不同数字相互抵消;
    • 假设数组中的元素与假设的target相等时,计数count加1;
    • 当计数count等于0时,说明在当前遍历到的数组元素中,当前假设的target与其他数字相互抵消(个数相同),所以我们重新假设下一个遍历的数组元素为target,继续上面过程。
    • 当遍历完数组后,target为所求数字。
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        target, count = nums[0], 1
        n = len(nums)

        for i in range(1, n):
            if nums[i] == target:
                count += 1
            else:
                count -= 1
                if count == 0:
                    target = nums[i]
                    count = 1
        
        return target
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值