More than half of the number of digital 39- array appears

Title: The number of times a digital array appears that more than half the length of the array, find this number.

def num_more_half(nums):
    if len(nums)<1:
        return None
    res = nums[0]
    cnt = 1
    for num in nums:
        if num == res:
            cnt += 1
        else:
            cnt -= 1
            if cnt == 0:
                res = num
                cnt = 1

    return res

Note:

Method 1: through a dictionary, iterate over the array, count the number of times each number appears, and then more than half of the number of digital output

Method 2: first take a certain number, such as the first digit, the subsequent traversal, using a variable count is counted. If appears again, count + 1, if the other numbers appear, then the count-1. When the count is 0, instead of the target figures with the current numbers, continue to the next iteration. The final target figure is the number of more than half of the figure.

Guess you like

Origin www.cnblogs.com/kingshine007/p/11360393.html