Find the most common entry in an array

前端 未结 8 1987
终归单人心
终归单人心 2020-12-07 10:43

You are given a 32-bit unsigned integer array with length up to 232, with the property that more than half of the entries in the array are equal to N, for some 32

8条回答
  •  Happy的楠姐
    2020-12-07 11:19

    Notice that if the sequence a0, a1, . . . , an−1 contains a leader, then after removing a pair of elements of different values, the remaining sequence still has the same leader. Indeed, if we remove two different elements then only one of them could be the leader. The leader in the new sequence occurs more than n/2 − 1 = (n−2)/2 times. Consequently, it is still the leader of the new sequence of n − 2 elements.

    Here is a Python implementation, with O(n) time complexity:

    def goldenLeader(A):
        n = len(A)
        size = 0
        for k in xrange(n):
            if (size == 0):
                size += 1
                value = A[k]
            else:
                if (value != A[k]):
                    size -= 1
                else:
                    size += 1
        candidate = -1
        if (size > 0):
            candidate = value
        leader = -1
        count = 0
        for k in xrange(n):
            if (A[k] == candidate):
                count += 1
        if (count > n // 2):
            leader = candidate
        return leader
    

提交回复
热议问题