题目
给出一个整数数组,找出所有超过n / 3次的数。算法时间复杂度必须是O(n),空间复杂度为O(1)。
Python题解
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
count1, count2, cn1, cn2 = 0, 0, 0, 1
for n in nums:
if n == cn1:
count1 += 1
elif n == cn2:
count2 += 1
elif count1 == 0:
count1, cn1 = 1, n
elif count2 == 0:
count2, cn2 = 1, n
else:
count1 -= 1
count2 -= 1
return [n for n in (cn1, cn2) if nums.count(n) > len(nums) // 3]