题目来源:169. 多数元素:https://leetcode-cn.com/problems/majority-element/
方法一:妙用排序法(不推荐)
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
a = -((-len(nums))// 2) - 1
return nums[a]
方法二:摩尔投票法
根据上述的算法思想,我们遍历投票数组,将当前票数最多的候选人与其获得的(抵消后)票数分别存储在 major 与 count 中。
当我们遍历下一个选票时,判断当前 count 是否为零:
- 若 count == 0,代表当前 major 空缺,直接将当前候选人赋值给 major,并令 count++
- 若 count != 0,代表当前 major 的票数未被完全抵消,因此令 count–,即使用当前候选人的票数抵消 major 的票数
py
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
major = 0
count = 0
for n in nums:
if count == 0:
major = n
if n == major:
count = count + 1
else:
count = count - 1
return major
go
func majorityElement(nums []int) int {
major := 0
count := 0
for _, num := range nums {
if count == 0 {
major = num
}
if major == num {
count += 1
} else {
count -= 1
}
}
return major
}
复杂度
- 时间复杂度:O(n)O(n),仅遍历一次数组
- 空间复杂度:O(1)O(1),没有使用额外空间