LeetCode229 多数元素 II
作者:互联网
通过消除元素的方法确定候选, 即候选元素可以被消除\(\frac{n}{3}\)次.
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
proposal_1, proposal_2, cnt_1, cnt_2, n = 0, 0, 0, 0, len(nums)
for i in range(n):
if cnt_1 > 0 and proposal_1 == nums[i]: cnt_1 += 1
elif cnt_2 > 0 and proposal_2 == nums[i]: cnt_2 += 1
elif cnt_1 == 0: proposal_1, cnt_1 = nums[i], 1
elif cnt_2 == 0: proposal_2, cnt_2 = nums[i], 1
else: cnt_1, cnt_2 = cnt_1 - 1, cnt_2 - 1
sum_1, sum_2 = 0, 0
for i in range(n):
if cnt_1 > 0 and nums[i] == proposal_1: sum_1 += 1
if cnt_2 > 0 and nums[i] == proposal_2: sum_2 += 1
ans = []
if sum_1 > n // 3: ans.append(proposal_1)
if sum_2 > n // 3: ans.append(proposal_2)
return ans
标签:cnt,nums,sum,元素,LeetCode229,II,elif,ans,proposal 来源: https://www.cnblogs.com/solvit/p/16505149.html