Find the element that repeats the most
- Given a list of numbers, find the element that is repeated the most number of times in array.
Solution - I
This uses a lambda function to count the occurrences of each item in a list, and find the max from among the count. Its a more straightforward approach, but performs poorly for a list with large no of elements.
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ # straightforward solution, but performs bad return max(nums, key=nums.count)
Solution - II
Following uses a more naiive approach; but is better in terms of performance.
class Solution(object): def majorityElement(self, nums): from collections import defaultdict mydict = defaultdict(int) for eachItem in nums: mydict[eachItem]+=1 max = -1 ret = 0 for key,val in mydict.items(): if val >= max: max = val ret = key return ret