Find the most common entry in an array

前端 未结 8 1923
终归单人心
终归单人心 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条回答
  • 2020-12-07 11:16

    Keep one integer for each bit, and increment this collection appropriately for each integer in the array.

    At the end, some of the bits will have a count higher than half the length of the array - those bits determine N. Of course, the count will be higher than the number of times N occurred, but that doesn't matter. The important thing is that any bit which isn't part of N cannot occur more than half the times (because N has over half the entries) and any bit which is part of N must occur more than half the times (because it will occur every time N occurs, and any extras).

    (No code at the moment - about to lose net access. Hopefully the above is clear enough though.)

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题