zoukankan      html  css  js  c++  java
  • leetcode169 Majority Element

     1 """
     2 Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
     3 You may assume that the array is non-empty and the majority element always exist in the array.
     4 Example 1:
     5 Input: [3,2,3]
     6 Output: 3
     7 Example 2:
     8 Input: [2,2,1,1,1,2,2]
     9 Output: 2
    10 """
    11 """
    12 自己的解法
    13 """
    14 class Solution:
    15     def majorityElement(self, nums):
    16         import collections
    17         d = dict(collections.Counter(nums))
    18         return max(d, key=lambda k: d[k])
    19 """
    20 别人的解法
    21 """
    22 class Solution:
    23     def majorityElement(self, nums):
    24         return sorted(nums)[len(nums)//2]
    25 
    26 """
    27 collections模块
    28 此模块 包含了 除了dict,set,list,tuple以外的 Python中的一些特殊容器
    29     OrderedDict类:排序字典,是字典的子类。引入自2.7。
    30     namedtuple()函数:命名元组,是一个工厂函数。引入自2.6。
    31     Counter类:为hashable对象计数,是字典的子类。引入自2.7。
    32     deque:双向队列。引入自2.4。
    33     defaultdict:使用工厂函数创建字典,使不用考虑缺失的字典键。引入自2.5。
    34 """
  • 相关阅读:
    jq---方法总结
    Coderfroces 862 B . Mahmoud and Ehab and the bipartiteness
    Coin
    joisino's travel
    日天的终生大事(dp)
    Codefroces 852 G. Bathroom terminal
    Codefroces432 div2 A,B,C
    Atcoder ABC 069 C
    Codefroces 849 A,B
    HDU 6186 CS Course
  • 原文地址:https://www.cnblogs.com/yawenw/p/12398727.html
Copyright © 2011-2022 走看看