3 Python methods: count, Counter and Sort


  • 0
    J
    class Solution(object):
        def majorityElement(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
    
            l = len(nums)
            for i in set(nums):
                if nums.count(i) > l/2.0:
                    return i
     
            return -1
     
        def majorityElement(self, nums):
     
            from collections import Counter
            c = Counter(nums)
            l = len(nums)
            for i in c.keys():
                if c.get(i, 0) > l/2.0:
                    return i
    
        def majorityElement(self, nums):
    
            nums = sorted(nums)
            return nums[len(nums)/2]
    

Log in to reply
 

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