方法一:哈希表计数
时间复杂度 :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/
