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/

相关推荐
CodeSheep程序羊4 分钟前
拼多多春节加班工资曝光,没几个敢给这个数的。
java·c语言·开发语言·c++·python·程序人生·职场和发展
2401_8414956410 分钟前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
budingxiaomoli10 分钟前
优选算法-字符串
算法
我是咸鱼不闲呀25 分钟前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
学历真的很重要25 分钟前
【系统架构师】第二章 操作系统知识 - 第二部分:进程与线程(补充版)
学习·职场和发展·系统架构·系统架构师
qq74223498429 分钟前
APS系统与OR-Tools完全指南:智能排产与优化算法实战解析
人工智能·算法·工业·aps·排程
A尘埃1 小时前
超市购物篮关联分析与货架优化(Apriori算法)
算法
.小墨迹1 小时前
apollo学习之借道超车的速度规划
linux·c++·学习·算法·ubuntu
不穿格子的程序员1 小时前
从零开始刷算法——贪心篇1:跳跃游戏1 + 跳跃游戏2
算法·游戏·贪心
大江东去浪淘尽千古风流人物1 小时前
【SLAM新范式】几何主导=》几何+学习+语义+高效表示的融合
深度学习·算法·slam