什么是摩尔投票:什么是摩尔投票?一个动画就讲清楚了? - 知乎
169. 多数元素
解题思路:投票的原理
1、遍历一遍
2、认为i位置为票数最多的,初始值times=1
3、下一个位置一样那就times+1,反之-1
4、如果times=0的时候,那我们就考虑这个人不是我们要选举的首领了,换为这个位置的值

# python3才有的类型限制
from typing import List
def moer(num_list: List[int]) -> int:
if not num_list:
return None
res = num_list[0]
times = 1
for i in num_list[1:]:
if times == 0:
res = i
times = 1
elif i == res:
times += 1
else:
times -= 1
return res
if __name__ == '__main__':
# 找的是list中出现次数最多的那个值,如果需要知道出现几次就不适合这个算法了
print(moer([1, 3, 3, 3, 2]))
print(moer([1, 3, 3, 4, 2])) # 3的存在没有超过半数就不符合题意了,结果也就不适用了
print(moer([]))
print(moer([1]))
print(moer([1, 2]))
剑指 Offer 39. 数组中出现次数超过一半的数字
class Solution:
def majorityElement(self, nums: List[int]) -> int:
target = nums[0]
times = 0
for n in nums[1:]:
if target == n:
times += 1
else:
times -= 1
if times == -1:
target = n
times = 0
return target
博客围绕使用摩尔投票法解决多数元素问题展开,介绍了169. 多数元素和剑指 Offer 39. 数组中出现次数超过一半的数字两道题。解题思路基于投票原理,通过遍历数组,根据元素是否相同对票数进行加减,当票数为0时更换候选元素。
615

被折叠的 条评论
为什么被折叠?



