-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajoritynormal.cpp
More file actions
57 lines (48 loc) · 1.26 KB
/
majoritynormal.cpp
File metadata and controls
57 lines (48 loc) · 1.26 KB
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
#include <iostream>
using namespace std;
class MajorityElement {
public:
int findCandidate(int arr[], int n) {
int candidate = arr[0], count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == candidate)
count++;
else
count--;
if (count == 0) {
candidate = arr[i];
count = 1;
}
}
return candidate;
}
bool isMajority(int arr[], int n, int candidate) {
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == candidate) count++;
}
return count > n / 2;
}
int getMajorityElement(int arr[], int n) {
int candidate = findCandidate(arr, n);
return isMajority(arr, n, candidate) ? candidate : -1;
}
};
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int* arr = new int[n];
cout << "Enter elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
MajorityElement obj;
int result = obj.getMajorityElement(arr, n);
if (result != -1)
cout << "Majority Element: " << result << endl;
else
cout << "No Majority Element found" << endl;
delete[] arr;
return 0;
}