数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5
示例 2:
输入:[3,2]
输出:-1
示例 3:
输入:[2,2,1,1,1,2,2]
输出:2
说明:
- 你有办法在时间复杂度为 O(N),空间复杂度为 O(1) 内完成吗?
Python 解答:
1.字典
class Solution:
def majorityElement(self, nums: List[int]) -> int:
length = len(nums)
adic = {}
for item in nums:
if item not in adic.keys():
adic[item] = 1
else:
adic[item] += 1
if adic[item] > length//2:
return item
else:
return -1
2.摩尔投票法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
major = None
count = 0
for it in nums:
if not count:
major = it
count = 1
elif it == major:
count += 1
else:
count -= 1
total = 0
for it in nums:
if it == major:
total += 1
return major if total > len(nums)//2 else -1
留言