python方法,利用字典
class Solution(object):
def majorityElement(self, nums):
judge = 0.5
num_dict={}
for i in range(len(nums)):
if nums[i] in num_dict:
num_dict[nums[i]] = num_dict[nums[i]] + 1
else:
num_dict[nums[i]] = 1
for num, counts in num_dict.items():
if counts*1.0/len(nums) > judge:
return num
O(n) time O(1) space fastest solution 的算法
class Solution(object):
def majorityElement(self, nums):
major = nums[0]
count = 1
for i in range(1, len(nums)):
if count == 0:
major = nums[i]
count = 1
elif major == nums[i]:
count = count + 1
else:
count = count - 1
return major