python 求众数 LeetCode N0.169

本文深入解析LeetCode第169题求众数的多种解法,包括使用计数器、摩尔投票算法及字典统计等方法,并附带Python代码实现,适合算法学习者及面试准备人员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python 求众数 LeetCode N0.169

这道题有很多解法官方leetcode上面是六种,由于说的太过于详细,我都不好意思,再补充什么了。所以我就写了一点,没看答案之前的写法,和我觉得,需要掌握的写法吧。他写的很多代码很精简,值得学习。(ps,纳闷的是,即使我用的O(n)的复杂度,排名也很靠后哈哈哈哈哈)

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #count = 0
        #candidate = None

        #for num in nums:
        #   if count == 0:
        #        candidate = num
        #    count += (1 if num == candidate else -1)

        #return candidate

        count = 0
        candidate = nums[0]
        for i in range(len(nums)):
            if nums[i] == candidate:
                count += 1
            else:
                count -= 1
            if count == 0:
                candidate =nums[i+1]
        return candidate
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        import math
        count = {}
        if len(nums) %2 == 1:
            n = len(nums)+1
        else :
            n = len(nums)
        for i in nums:
            count[i] = count.get(i,0) + 1
            
            if count[i] >= n/2:
                return i
        for i in nums:
            if count[i] >= n/2:
                return i
class Solution:
    def majorityElement(self, nums):
        counts = collections.Counter(nums)
        return max(counts.keys(), key=counts.get)

#作者:LeetCode
#链接:https://leetcode-cn.com/problems/majority-element/solution/qiu-zhong-shu-by-leetcode-2/
#来源:力扣(LeetCode)
#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值