The number of occurrences in arrays is more than half.

Title Description

One number in the array appears more than half of the length of the array. Please figure out this number. For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. As the number 2 appears in the array 5 times, more than half of the array length, so output 2. If it does not existThe output is 0.

thinking

Similar to the previous several problem arrays and strings, it uses python’s count counting method, or the Counter method of the collection module.

Answer

Method 1

class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        for num in numbers:
            if numbers.count(num)>(len(numbers)/2):
                return num
        return 0

Method two

import collections
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        dic = collections.Counter(numbers)
        for key,value in dic.items():
            if value>(len(numbers)/2):
                return key
        return 0

 

Leave a Reply

Your email address will not be published. Required fields are marked *