【leetcode-python-13-分治算法】面试题39. 数组中出现次数超过一半的数字
leetcode 面试题39. 数组中出现次数超过一半的数字
参考大佬版1(53.01%)
摩尔投票法: 核心理念为 “正负抵消” 。
票数和:由于众数出现的次数超过数组长度的一半;若记 众数 的票数为+1,非众数 的票数为−1,则一定有所有数字的 票数和 >0。
注:参考题解区Krahets思路。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
votes = 0
for num in nums:
if votes == 0:
x = num
if num == x:
votes = votes + 1
else:
votes = votes - 1
return x
参考大佬版(68.08%)
换一个简便的写法。
注:参考题解区Krahets思路。
class Solution(object):
def majorityElement(self, nums):
votes = 0
for num in nums:
if votes == 0: x = num
votes += 1 if num == x else -1
return x
新手入坑,多多包涵~~