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
//! Boyer--Moore's majority vote algorithm。

/// Boyer--Moore's majority vote algorithm。
///
/// 過半数の出現数を持つ要素があれば、それを返す。
///
/// # Idea
/// `todo!()`
///
/// # Complexity
/// $O(n)$ time.
///
/// # Examples
/// ```
/// use nekolib::algo::majority;
///
/// assert_eq!(majority(&[1, 1, 3, 2, 1]), Some(&1));
/// assert_eq!(majority(&[9]), Some(&9));
/// assert_eq!(majority(&[6, 7]), None);
/// assert_eq!(majority::<i32>(&[]), None);
/// ```
pub fn majority<T: Eq>(buf: &[T]) -> Option<&T> {
    if buf.is_empty() {
        return None;
    }
    let mut maj = &buf[0];
    let mut vote = 1;
    let n = buf.len();
    for x in buf.iter().skip(1) {
        if maj == x {
            vote += 1;
        } else if vote == 0 {
            maj = x;
            vote = 1;
        } else {
            vote -= 1;
        }
    }
    let mut vote = 0;
    let mut first = 0;
    for (i, x) in buf.iter().enumerate().rev() {
        if maj == x {
            vote += 1;
            first = i;
        }
    }
    if vote > n - vote {
        Some(&buf[first])
    } else {
        None
    }
}