-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq17.10.cpp
56 lines (40 loc) · 1.11 KB
/
q17.10.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
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
int find_majority_elem(vector<int> &inData) {
int match_mismatch = 0, majority_elem = -1;
// int majority_elem, majority_elem_freq;
cout << "input data is: " << endl;
for (auto &elem : inData)
cout << elem << ", ";
cout << endl;
majority_elem = inData[0];
for (vector<int>::iterator iter = inData.begin(); iter != inData.end();
iter++) {
if (majority_elem == *iter)
match_mismatch++;
else
match_mismatch--;
if (match_mismatch == 0) {
if (!((iter + 1) == inData.end()))
majority_elem = *(iter + 1);
}
}
if (match_mismatch == 0)
return -1;
int maj_freq = 0;
for (auto &elem : inData)
if (elem == majority_elem)
maj_freq++;
if (maj_freq > (int)(inData.size() / 2))
return majority_elem;
else
return -1;
}
int main(void) {
vector<int> inData{1, 2, 5, 9, 5, 5, 5};
int majority_elem = find_majority_elem(inData);
cout << "majority element is: " << majority_elem << endl;
return 0;
}