More than half of the number 28. The digital array appears
problem:
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.
solve:
thought:
Counting this problem, we only need to record the accumulated value by dictionary, and finally to see whether each accumulated value exceeds n / 2, on it.
python code:
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
n=len(numbers)//2
dic={}
for i in numbers:
if(dic.get(i)==None):
dic[i]=1
else:
dic[i]+=1
for j in dic:
if(dic[j]>n):
return j
return 0