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.
code1:
from operator import *
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict1 = {}
for i in range(len(nums)):
dict1[nums[i]] = dict1.get(nums[i], 0) + 1
dict1 = sorted(dict1.iteritems(), key = itemgetter(1), reverse = True)
return dict1[0][0]
code2:
借鉴了Moore投票算法,速度较前者更快
class Solution:
def majorityElement(self, nums):
candidate = None
count = 0
for e in nums:
if count == 0:
candidate = e
count = 1
elif e == candidate:
count += 1
else:
count -= 1
return candidate