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 """