-
Notifications
You must be signed in to change notification settings - Fork 78
/
EquiLeader.cs
50 lines (49 loc) · 1021 Bytes
/
EquiLeader.cs
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
using System;
class Solution {
public int solution(int[] A) {
int leader = -1;
switch (A.Length) {
case 0:
break;
case 1:
leader = A[0];
break;
case 2:
if(A[0] == A[1])
leader = A[0];
break;
default:
int size = 0, value = 0;
for (var i = -1; ++i < A.Length;) {
if (size == 0) {
++size;
value = A[i];
}
else if (value != A[i])
--size;
else
++size;
}
if (size > 0) {
int count = 0;
for (var i = -1; ++i < A.Length;)
if (A[i] == value && ++count > A.Length >> 1) {
leader = A[i];
break;
}
}
break;
}
int equiLeaders = 0;
if (leader != -1) {
var counter = new int[A.Length];
var current = 0;
for (var i = -1; ++i < A.Length; counter[i] = A[i] == leader ? ++current : current)
;
for (var i = 0; ++i < A.Length;)
if (counter[i - 1] > i >> 1 && counter[A.Length - 1] - counter[i - 1] > A.Length - i >> 1)
++equiLeaders;
}
return equiLeaders;
}
}