-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEquiLeader.cpp
More file actions
38 lines (36 loc) · 915 Bytes
/
Copy pathEquiLeader.cpp
File metadata and controls
38 lines (36 loc) · 915 Bytes
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
#include <unordered_map>
using namespace std;
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
int length = A.size();
unordered_map<int, int> mp;
// Find the majority element
// and count occurances of all elements in one loop
int majority;
int count = 0;
for (int i = 0; i < length; ++i) {
if (count == 0) {
majority = A[i];
count++;
} else if (majority == A[i]) {
count++;
} else {
count--;
}
mp[A[i]]++;
}
// find indexes
int res = 0;
int total_count = mp[majority];
int curr_count = 0;
for (int i = 0; i < length; ++i) {
if (A[i] == majority) {
curr_count++;
}
if (2 * curr_count > i + 1 &&
2 * (total_count - curr_count) > length - i - 1) {
res++;
}
}
return res;
}