【发布时间】:2020-05-31 18:39:18
【问题描述】:
我想使用分治算法从列表中找到多数元素。
我在 Leetcode 上看到了这个解决方案的代码:
class Solution:
def majorityElement(self, nums, lo=0, hi=None):
def majority_element_rec(lo, hi):
# base case; the only element in an array of size 1 is the majority
# element.
if lo == hi:
return nums[lo]
# recurse on left and right halves of this slice.
mid = (hi-lo)//2 + lo
left = majority_element_rec(lo, mid)
right = majority_element_rec(mid+1, hi)
# if the two halves agree on the majority element, return it.
if left == right:
return left
# otherwise, count each element and return the "winner".
left_count = sum(1 for i in range(lo, hi+1) if nums[i] == left)
right_count = sum(1 for i in range(lo, hi+1) if nums[i] == right)
return left if left_count > right_count else right
return majority_element_rec(0, len(nums)-1)
当有多数元素时,结果是正确的,当没有这样的元素时,它返回错误的结果。
我尝试将return语句更改为:
if left_count > right_count:
return left
elif left_count < right_count:
return right
else:
return -1
所以当没有正确答案时它返回-1。
当输入为[1,2,1,3] 时,结果为-1(正确答案),但当输入为[1,2,3,3] 时,输出为3,这是错误的。
似乎每个人都使用此解决方案,但它不起作用。关于如何解决它的任何想法?
TIA
【问题讨论】:
-
请注意,在problem specification 中它说“您可以假设数组是非空的并且多数元素始终存在于数组中。”。你是对的,如果没有多数元素,这个算法将不起作用。
-
我可能跳过了它,关于如何更改它以便在没有多数元素时返回 -1 的任何想法?
标签: python python-3.x divide-and-conquer