每天(?)一道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 [n/2] 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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,951评论 0 23
  • 传说 有情人终成眷属 传说里总是会有 一见钟情 想断桥上 不变千年的风景 只是当时 他们不知道 他们将会是 传诵千...
    塞纳琉斯阅读 221评论 0 0
  • 需要勇气去做一些像做的事情。 可是宝贝的预告来临,让我欢喜不已,同时也战战兢兢。 不敢丝毫的怠慢。 宝贝,妈妈说你...
    四先生幸福开始阅读 110评论 0 0
  • 【幸福女孩 糖糖 一年级 坚持原创分享第314天 2018.7.17 星期二】 今天上钢琴课的时候,田老师...
    何亚珂阅读 157评论 0 0