每天(?)一道Leetcode(15) Majority Element

Array

169.Majority Element

(昨天回家过年堵在路上所以断更了,难受)
Given an array of size n, find the majority element. The majority element is the element that appears more than times.

You may assume that the array is non-empty and the majority element always exist in the array.

返回众数

Solutions

利用collections.Counter可以得到元素与元素出现次数对应的字典,将字典按照出现次数降序排序,返回第一个元素

class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sorted(collections.Counter(nums).items(), key=lambda a: a[1], reverse=True)[0][0]

class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return collections.Counter(nums).most_common(1)[0][0]  ###.most_common方法

Counter常用方法


# elements() 按照counter的计数,重复返回元素
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
 
# most_common(n) 按照counter的计数,按照降序,返回前n项组成的list; n忽略时返回全部
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
 
# subtract([iterable-or-mapping]) counter按照相应的元素,计数相减
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)

你可能感兴趣的:(每天(?)一道Leetcode(15) Majority Element)