leetcode之Majority Element II

来源:互联网 发布:林少华 知乎 编辑:程序博客网 时间:2024/05/21 17:39

majority element 2比1的不同在于1:不再是一定存在元素;2:由n/2变为n/3。1的可以排序直接查中间的元素来做,2就不行了。祭出来Counter就十分轻松啦。代码如下:

class Solution(object):    def majorityElement(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        from collections import Counter        if nums == []:            return []        a = Counter(nums)        b = []        for i in a.keys():            if a[i] > len(nums) / 3:                b.append(i)        return b
实际上可以把一开始的空集判断也是正确的。

0 0
原创粉丝点击