-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdominator.rs
49 lines (43 loc) · 1.01 KB
/
dominator.rs
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
struct Dominator;
impl Dominator {
fn solution(a: &Vec<i32>) -> i32 {
let mut candidate = -1;
let mut size = 0;
for e in a {
if size == 0 {
size += 1;
candidate = *e;
} else {
if candidate == *e {
size += 1;
} else {
size -= 1;
}
}
}
if size > 0 {
let mut index = -1_i32;
let mut count = 0;
for i in 0..a.len() {
if a[i] == candidate {
count += 1;
if index == -1 {
index = i as i32;
}
}
}
if count > a.len() / 2 {
return index;
}
}
-1
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dominator() {
assert_eq!(Dominator::solution(&vec![3, 4, 3, 2, 3, -1, 3, 3]), 0);
}
}