Equivalence testing of n objects

前端 未结 4 1268
一向
一向 2021-01-07 05:20

Assume that we are given \'n\' objects and a subroutine that takes two inputs and says if they are equivalent or not (e.g. it can give output as 1 if they are equal).

<
4条回答
  •  醉话见心
    2021-01-07 05:46

    You can use the Boyer-Moore majority voting algorithm, which does at most n-1 comparisons.

    function find_majority(A)
        majority = None
        count = 0
        for a in A:
            if count == 0
                majority = a
            else if a == majority
                count += 1
            else
                count -= 1
        return majority
    

    It returns the most common element if appears more than n/2 times in the array.

    If you need to know if there is a majority item, then you can make a second pass through the array counting how many times the value returned from the find_majority function appears. This adds another n comparisons.

提交回复
热议问题