forked from usamajay/hacktoberfest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MajorityElement.cpp
71 lines (55 loc) · 1.22 KB
/
MajorityElement.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//Cpp code for getting output of the element which occures more than n/3 times in an array.
#include <bits/stdc++.h>
using namespace std;
int appearsNBy3(int arr[], int n)
{
int count1 = 0, count2 = 0;
int first=INT_MAX , second=INT_MAX ;
for (int i = 0; i < n; i++) {
// if this element is previously seen,
// increment count1.
if (first == arr[i])
count1++;
// if this element is previously seen,
// increment count2.
else if (second == arr[i])
count2++;
else if (count1 == 0) {
count1++;
first = arr[i];
}
else if (count2 == 0) {
count2++;
second = arr[i];
}
// if current element is different from
// both the previously seen variables,
// decrement both the counts.
else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
// Again traverse the array and find the
// actual counts.
for (int i = 0; i < n; i++) {
if (arr[i] == first)
count1++;
else if (arr[i] == second)
count2++;
}
if (count1 > n / 3)
return first;
if (count2 > n / 3)
return second;
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 1, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << appearsNBy3(arr, n) << endl;
return 0;
}