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/

相关推荐
练习时长一年1 小时前
LeetCode热题100(乘积最大子序列)
数据结构·算法·leetcode
仰泳的熊猫1 小时前
题目1109:Hanoi双塔问题
数据结构·c++·算法·蓝桥杯
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——LeetCode 295 题:数据流的中位数
算法·结构与算法
闪电麦坤951 小时前
Leecode热题100:合并区间(数组)
数据结构·算法·leecode
VT.馒头2 小时前
【力扣】2631. 分组
javascript·算法·leetcode·typescript
永远都不秃头的程序员(互关)2 小时前
【K-Means深度探索(四)】速度与激情:MiniBatch K-Means如何驯服海量数据
算法·机器学习·kmeans
中國龍在廣州2 小时前
35天,成了AI 模型的斩杀线
大数据·人工智能·深度学习·算法·机器人
多米Domi01110 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
罗湖老棍子11 小时前
【例4-11】最短网络(agrinet)(信息学奥赛一本通- P1350)
算法·图论·kruskal·prim