To prove safety offer - numbers appear repeatedly in the array

Title Description

There are a number of array number that appears more than half the length of the array, find this number. For example, a length of the input array 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears five times, more than half the length of the array in the array, the output 2. If there is 0 output.

Thinking

This nothing to say, using a dictionary to store the number of individual elements like 

# -*- coding:utf-8 -*-
import collections
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        n = len(numbers)//2
        nums = collections.defaultdict(lambda:0)
        for num in numbers:
            nums[num] += 1
        values = nums.values()
        maxi = max(values)
        if maxi>n:
            for key in nums.keys():
                if nums[key] == maxi:
                    return key
        else:
            return 0

 

Published 82 original articles · won praise 2 · Views 4361

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104761284