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