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/

相关推荐
AGV算法笔记6 分钟前
CVPR 2025 最新感知算法解读:GaussianLSS 如何用 Gaussian Splatting 重构 BEV 表示?
算法·重构·自动驾驶·3d视觉·感知算法·多视角视觉
勤劳的进取家1 小时前
数据链路层基础
网络·学习·算法
Advancer-1 小时前
第二次蓝桥杯总结(上)
java·算法·职场和发展·蓝桥杯
ん贤2 小时前
加密算法(对称、非对称、哈希、签名...)
算法·哈希算法
superior tigre2 小时前
78 子集
算法·leetcode·深度优先·回溯
天威?*2 小时前
bitset的数据结构用法
算法·动态规划
hoiii1873 小时前
粒子滤波跟踪系统 - 蒙特卡洛方法实现
算法
weisian1513 小时前
Java并发编程--47-分布式ID生成器:雪花算法(Snowflake)与时钟回拨问题
java·算法·时钟回拨·雪花算法id
itzixiao3 小时前
L1-066 猫是液体(5分)[java][python]
java·开发语言·python·算法
ytttr8734 小时前
MATLAB SIFT图像配准实现
算法·机器学习·matlab