class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n = len(nums)
res = []
# 存储两位候选人及计票【非他们的选票数】
cand1 = nums[0]
cand2 = nums[0]
count1 = 0
count2 = 0
if n == 0:
return res
# 配对阶段
for num in nums:
if cand1 == num:
count1 += 1
continue
if cand2 == num:
count2 += 1
continue
if count1 == 0:
cand1 = num
count1 += 1
continue
if count2 == 0:
cand2 = num
count2 += 1
continue
# 不相等则要抵消
count1 -= 1
count2 -= 1
# 计数,判断是否票数大于 n/3
count1 = 0
count2 = 0
for num in nums:
if cand1 == num:
count1 += 1
elif cand2 == num:
count2 += 1
if count1 > n/3:
res.append(cand1)
if count2 > n/3:
res.append(cand2)
return res
每日一道Leetcode - 229. 求众数 II 【摩尔投票法】
最新推荐文章于 2024-09-06 09:22:51 发布