思路:一种思路是进行排序,另一种是哈希表。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
d={}
temp_max=0
temp_max_num=None
for num in nums:
if d.get(num)!=None:
d[num]+=1
if d[num]>=n/2+1:
return num
elif d[num]>temp_max:
temp_max=d[num]
temp_max_num=num
else:
d[num]=1
if d[num]>temp_max:
temp_max=d[num]
temp_max_num=num
return temp_max_num