题目描述:
如果数组中多一半的数都是同一个,则称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5
示例 2:
输入:[3,2]
输出:-1
解法一:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums is None:
return -1
nums.sort()
mid=len(nums)//2
if nums.count(nums[mid])>len(nums)//2:
return nums[mid]
else:
return -1
解法二:摩尔算法
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
major = nums[0]
count = 1
for x in nums[1:]:
if count == 0:
major = x
if x == major:
count = count + 1
else:
count = count - 1
return major
解法三:哈希计数法
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
countMap = {}
for i in nums:
if i not in countMap.keys():
countMap[i] = 1
else:
countMap[i] += 1
flag = False
for key, value in countMap.items():
if value > len(nums) / 2:
flag = True
return key
if flag:
return -1