【问题标题】:Majority element using divide&conquer使用分而治之的多数元素
【发布时间】: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


【解决方案1】:

我认为递归步骤是可以的,因为如果有多数元素,它必须是数组中至少一半的多数元素,并且递归步骤会找到它。如果没有多数元素,递归算法仍然会返回一个(错误的)候选者。

如果你想让程序检测元素是否确实是多数元素, 我只想改变最后一步。

def majorityElement(self, nums):
    ...
    candidate = majority_element_rec(0, len(nums)-1)
    if nums.count(candidate) > len(nums)//2:
        return count
    else:
        return -1

或者,递归步骤可以通过替换最后一行来执行相同的检查是否找到的候选确实是多数元素:

return left if left_count > right_count else right

majority = ((hi - lo) + 1) / 2
if left_count > majority:
     return left
if right_count > majority:
     return right
return -1

这应该仍然有效,因为多数元素(如果存在)必须递归地是一半数组中的多数元素,因此必须仍然传播。

【讨论】:

  • 我想这样做,但我担心这不再被视为分治算法,因为您手动检查了最后一项。
  • @RoyAncri 这就像主函数的子程序是分而治之
猜你喜欢
  • 2018-10-16
  • 2018-08-05
  • 2020-01-07
  • 2019-11-05
  • 2016-08-16
  • 2016-02-05
  • 2014-10-20
  • 1970-01-01
相关资源
最近更新 更多