没看答案,哈希表法。时间复杂度O(n),空间复杂度O(n)。
from collections import defaultdict
class Solution:
def majorityElement(self, nums: List[int]) -> int:
n = len(nums)
count = defaultdict(int)
for num in nums:
count[num] += 1
if count[num] >= n // 2 + 1:
return num
return -1
摩尔投票法,时间复杂度O(n),空间复杂度O(1):
- 假设不同数字相互抵消,那么最后剩下的数字,就是我们要找的多数元素。
- 我们可以把这个过程打个比方,比如现在多军对峙,假设阵营A士兵人数比其他方的人数都多,阵营A士兵能以一杀一,那么只要阵营A士兵不杀自己人(相同数字),去杀不同阵营的人(不同数字),那么最后剩下的那些士兵,就是阵营A的士兵。
- 因此我们可以假设数组的第一个数字为target,然后遍历数组,我们尝试用计数count模拟这个抵消的过程,规则如下:
- 当数组中的元素与假设的target不相等时,计数count减1,即模拟不同数字相互抵消;
- 假设数组中的元素与假设的target相等时,计数count加1;
- 当计数count等于0时,说明在当前遍历到的数组元素中,当前假设的target与其他数字相互抵消(个数相同),所以我们重新假设下一个遍历的数组元素为target,继续上面过程。
- 当遍历完数组后,target为所求数字。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
target, count = nums[0], 1
n = len(nums)
for i in range(1, n):
if nums[i] == target:
count += 1
else:
count -= 1
if count == 0:
target = nums[i]
count = 1
return target