Leetcode: Majority Element
1 min readDec 27, 2016
We need to find the element whose count is more than half the number of elements in given array
- Create a dictionary to keep count of each number in the array
- Traverse the array and update counters
- Exit as soon as counter of a number exceeds half of length
Remarks:
- O(n) time complexity as we are traversing the array
- O(1) space complexity as only constant number of variables are used
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = {}
l = len(nums) / 2
for n in nums:
dp[n] = dp[n] + 1 if n in dp else 1
if dp[n] > l:
return n