169. 多数元素 - 力扣(LeetCode)

方法一:哈希表计数

时间复杂度 :O(n)
空间复杂度:O(n)

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 13:28 
# "Stay hungry,stay foolish."

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        from collections import Counter

        counts = Counter(nums)
        n = len(nums)
        for num,count in counts.items():
            if count > n//2:
                return num

方法二:排序法

时间复杂度 :O(n log n)(排序)
空间复杂度:O(1)(如果原地排序)

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 13:28 
# "Stay hungry,stay foolish."

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return nums[len(nums)//2]

方法三:随机化(概率法)

期望时间复杂度 :O(n)(平均情况)
最坏时间复杂度 :理论上可能无限(但概率极低)
空间复杂度:O(1)

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 13:28 
# "Stay hungry,stay foolish."
import random


class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        while True:
            candidate = random.choice(nums)
            if nums.count(candidate) > n//2:
                return candidate

结果

解题步骤:https://www.bilibili.com/video/BV1QarCByEKS/

相关推荐
熊猫_豆豆9 小时前
YOLOP车道检测
人工智能·python·算法
艾莉丝努力练剑9 小时前
【Linux:文件】Ext系列文件系统(初阶)
大数据·linux·运维·服务器·c++·人工智能·算法
偷吃的耗子10 小时前
【CNN算法理解】:CNN平移不变性详解:数学原理与实例
人工智能·算法·cnn
dazzle11 小时前
机器学习算法原理与实践-入门(三):使用数学方法实现KNN
人工智能·算法·机器学习
那个村的李富贵11 小时前
智能炼金术:CANN加速的新材料AI设计系统
人工智能·算法·aigc·cann
张张努力变强11 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发11 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
张登杰踩11 小时前
MCR ALS 多元曲线分辨算法详解
算法
YuTaoShao11 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波00712 小时前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc