Majority element
November 5, 2022
array-and-hashmapProblem URL: Majority element
We can count all element in the array, and return the element that has the most count.
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = collections.defaultdict(int)
for num in nums:
count[num] += 1
return max(count, key=count.get)
Time Complexity: O(n)
Space Complexity: O(n)