Problem Link : ELEM01
Problem :
Given an array, find the element which appears more than half of the size of array, and if there is no element found return None.
Input Format
First line contains the size of the array n
Constraints
1 ≤ n ≤ 10000
Output Format
Print the Element if found , else print None
Sample Input 1
9
3 3 4 2 4 4 2 4 4
Sample Output 1
4
Explanation 1
4 comes 5 times which is greater the half of the size of array.
Sample Input 2
8
3 3 4 2 4 4 2 4
Sample Output 2
None
Explanation 2
4 comes 4 times but it is not greater than the size of the array.
Solution:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int k=0,i,j,n,arr[50],b[50],count[50],x=0;
cin>>n;
for(i=0;i<n;i++)
cin>>arr[i];
for ( i = 0; i < n; i++) {
j = 0;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
{
b[k]=arr[i];
k++;
}
}
for(j=0;j<k;j++)
{ count[j]=0;
for(i=0;i<n;i++)
{
if(b[j]==arr[i])
count[j]++;
}
}
for(j=0;j<k;j++)
{
if(count[j]>(n/2))
{
cout<<"\n\n" << b[j];
x=1;
}
}
if(x!=1)
cout<<"None";
return 0;
}