问题描述
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.
解决方案
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num_dict = {}
for i in nums:
if i in num_dict:
num_dict[i] +=1
else:
num_dict[i] = 1
return max(num_dict.items(), key=lambda x: x[1])[0]
思路说明
建立一个字典统计每个元素出现次数,返回值最大的键。