Easy
給定序列長度為n,尋找它的眾數(shù)。眾數(shù)是在序列中出現(xiàn)n/2次以上的數(shù)铲球。假設(shè)給定序列不空挺庞,眾數(shù)一定存在
Solution:
方法一: 數(shù)數(shù)嘍。需要借助別的package, 效率不高稼病。
from collections import Counter
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = Counter(nums)
count_values = count.values()
return count.keys()[count_values.index(max(count_values))]
方法二:借助字典
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = {}
for num in nums:
if num not in dic:
dic[num]=1
if dic[num] > len(nums)//2: return num
else: dic[num]+=1