229. Majority Element II
Medium
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times.
Note: The algorithm should run in linear time and in O(1) space.
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
temp = {}
for n in nums:
if n in temp:
temp[n] += 1
else:
temp[n] = 1
majority = len(nums) // 3
ans = []
for n,count in temp.items():
if count > majority:
ans.append(n)
return ans
Last updated
Was this helpful?