Python solution using Dictionary(HashMap)


  • 0
    B
    class Solution(object):
        def majorityElement(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            
            #iterate and add to a map, keep track of max
            if nums is None or len(nums) == 0:
                raise Exception("Invalid Input")
            
            dc = dict()
            maxElem = nums[0]
            maxCt = 1
            dc[maxElem] = 1
            
            for k in xrange(1, len(nums)):
                elem = nums[k]
                if elem in dc:
                    ct = dc[elem] + 1
                    if ct > maxCt:
                        maxCt = ct
                        maxElem = elem
                        
                    dc[elem] = ct
                else:
                    dc[elem] = 1
            
            
            return maxElem
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.