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/

相关推荐
residual_fan4 小时前
持续对比强化学习(Continual Contrastive Reinforcement Learning)论文分享
人工智能·算法·数据挖掘·数据分析
s_w.h4 小时前
【 计网 】序列化与反序列化
linux·服务器·网络·算法·bash
信奥卷王4 小时前
2025年09月GESPC++五级真题解析(含视频)
算法
白狐_7984 小时前
408 数据结构|外部排序:流程与 k 路归并
数据结构·算法
闻缺陷则喜何志丹5 小时前
【动态规划】P3609 [USACO17JAN] Hoof, Paper, Scissor G
c++·算法·动态规划·洛谷
leihefeng5 小时前
手写数字识别:KNN vs 逻辑回归实战
python·算法·机器学习·逻辑回归·scikit-learn
全栈技术负责人6 小时前
DeepSeek Harness 业务工具权限插件 dsh-tool-permission设计思路
网络·算法·ai·ai编程
mmmmath_36 小时前
面试题 02.07. 链表相交
算法·链表
圣保罗的大教堂6 小时前
leetcode 3903. 最小稳定下标 I 简单
leetcode
residual_fan6 小时前
特征级SMOTE(Feature-level SMOTE)论文分享
人工智能·算法·数据挖掘·数据分析