时间不够,只能背诵哎,没办法,难题不写,简单题和中等题。
def majorityElement(nums):
# 使用字典 count 来记录每个元素的出现次数
count = {}
for num in nums:
if num in count:
count[num] += 1
else:
count[num] = 1
length = len(nums)
# 遍历字典,找到出现次数超过 n/2 的元素
for key in count:
if count[key] > length/2:
return key # 返回多数元素
# 测试示例
nums = [3, 3, 4, 2, 4, 4, 2, 4, 4]
print(majorityElement(nums)) # 输出: 4