Python solution using Counter


  • 0
    S
    from collections import Counter
    
    class Solution(object):
        def majorityElement(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            return [n for n in set(nums) if Counter(nums)[n] >len(nums)/3]
    

  • 0
    S

    I am sure this is not O(1) space.


  • 0
    M
    return [x[0] for x in Counter(nums).most_common(2) if x[1] > len(nums) / 3]
    

    could be better, but still O(n) space


Log in to reply
 

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