forked from Dverma1650/Hacktoberfest_2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Majority Element
55 lines (55 loc) · 813 Bytes
/
Majority Element
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<bits/stdc++.h>
using namespace std;
int majorityElement(int arr[], int n)
{
int count = 1, res = 0;
for(int i = 1; i < n; i++)
{
if(arr[res] == arr[i])
{
count++;
}
else
{
count--;
}
if(count == 0)
{
res = i;
count = 1;
}
}
count = 0;
for(int i = 0; i < n; i++)
{
if(arr[res] == arr[i])
{
count++;
}
}
if(count > n/2)
{
return arr[res];
}
else
{
return -1;
}
}
int main()
{
int T;
cin >> T;
while(T--)
{
int N;
cin >> N;
int arr[N];
for(int i = 0; i < N; i++)
{
cin >> arr[i];
}
cout << majorityElement(arr, N) << endl;
}
return 0;
}