第一种解法哈希表法或者字典法,空间复杂度o(n),时间复杂度O(n)
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
zd = {}
for i in nums:
if i not in zd:
zd[i] = 1
if zd[i] > n / 2:
return i
else:
zd[i] += 1
if zd[i] > n / 2:
return i
···
第二种解法:
排序 以后 出现超过一半的次数的数字一定在中间位置,时间复杂度就是排序的0(nlogn)空间复杂度O(1)
···
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return nums[len(nums)/2]
···
第三种解法:将数组一分为二,左边出现最多的为A,右边出现的最多为B,如果A=B,那么结果为A,如果A不等于B,那么,顺序扫描整个表格,分别计算AB个数,然后返回大的那个
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
begin = 0
end = len(nums) - 1
return self.helper(nums,begin,end)
def helper(self, nums, begin, end):
if begin == end:
return nums[begin]
elif begin < end:
mid = (begin + end) / 2
left = self.helper(nums,begin, mid)
right = self.helper(nums, mid + 1, end)
if left == right:
return left
else:
leftcount = 0
rightcount = 0
for i in range(begin,end+1):
if nums[i] == left:
leftcount += 1
elif nums[i] == right:
rightcount += 1
if leftcount < rightcount:
return right
else:
return left