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.
思路:
将列表中的数值进行一个出现次数的统计,然后判断出现最多次数的元素次数是否满足条件,是则输出。(这里用了2个for循环,效率不是很高,提交时速度只打败了50%不到的其他提交者,还有很大改进的余地)
代码:
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
dic[nums[i]] += 1
else:
dic[nums[i]] = 1
HighValue = 0
HighKey = None
for each in dic:
if dic[each] > HighValue:
HighValue = dic[each]
HighKey = each
if HighValue>len(nums)//2:
return HighKey