class Solution:
def majorityElement(self, nums: List[int]) -> int:
# 使用摩尔投票法
count = 0
candidate = 0
for num in nums:
if count == 0:
#当前没有候选人拉
candidate = num
count += 1
elif candidate == num:
# 还是出现与当前候选人一样
count += 1
else:
# 不是candidate,抵消
count -= 1
# 如果count>0的情况
if count > 0:
c = 0
for num in nums:
if num == candidate:
c += 1
if c > len(nums)/2:
return candidate
return -1
每日一道Leetcode - 面试题 17.10. 主要元素 【摩尔投票法】
最新推荐文章于 2024-09-20 09:09:17 发布