1. 算法步骤
- 维护候选众数
candidate
以及该候选的出现次数count
;
初始化:candidate
为任意值,count
为0; - 遍历数组
nums
, 对于每个元素x
:
1). 若count == 0
,则candidate = x
;
2). 若x == candidate x
,则count++
;否则count--
; - 遍历完成后,
candidate
即为整个数组nums
的众数。
2. 代码实现
class Solution:
def majorityElement(self, nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
## 作者:LeetCode-Solution
## 链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/