Problem
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Algorithm
When an element's frequency is not among the top two, its count is reset to zero. Otherwise, the algorithm continues tracking that element. This process retains two candidate elements whose potential frequencies may exceed ⌊n/3⌋, followed by a final validation step to confirm whether both have reached the threshold.
Code
python3
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
num1, num2 = None, None
cnt1, cnt2 = 0, 0
for num in nums:
if num1 == num:
cnt1 += 1
elif num2 == num:
cnt2 += 1
elif cnt1 == 0:
num1 = num
cnt1 = 1
elif cnt2 == 0:
num2 = num
cnt2 = 1
else:
cnt1 -= 1
cnt2 -= 1
cnt1, cnt2 = 0, 0
for num in nums:
if num1 == num:
cnt1 += 1
if num2 == num:
cnt2 += 1
ans = []
if cnt1 > len(nums) // 3:
ans.append(num1)
if cnt2 > len(nums) // 3:
ans.append(num2)
return ans