数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
方法一:摩尔排序法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
votes=0
for num in nums:
if votes==0:
x=num
if num ==x:
votes +=1
else:
votes -=1
return x
方法二:哈希表法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
if not nums:
return None
if len(nums) == 1:
return nums[0]
big={}
for num in nums:
if num not in big:
big[num]=1
else:
big[num] +=1
if big[num] > (len(nums)/2):
return num
return None