|
| 1 | +/** |
| 2 | + * [169] Majority Element |
| 3 | + * |
| 4 | + * Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. |
| 5 | + * |
| 6 | + * You may assume that the array is non-empty and the majority element always exist in the array. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * |
| 11 | + * Input: [3,2,3] |
| 12 | + * Output: 3 |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * |
| 16 | + * |
| 17 | + * Input: [2,2,1,1,1,2,2] |
| 18 | + * Output: 2 |
| 19 | + * |
| 20 | + * |
| 21 | + */ |
| 22 | +pub struct Solution {} |
| 23 | + |
| 24 | +// submission codes start here |
| 25 | + |
| 26 | +/* |
| 27 | + 抄的题解:Boyer-Moore Voting Algorithm |
| 28 | + 自己只能想到 HashMap 和排序, 真是太鸡儿菜了... |
| 29 | +
|
| 30 | + Boyer-Moore Voting Algorithm 的思路是假设当前值为主元素, 碰到当前值则 +1, 非当前值则 -1, 计数器一旦归零, |
| 31 | + 就取下一个数为主元素 |
| 32 | +
|
| 33 | + 最后留下的数一定主元素 |
| 34 | +
|
| 35 | + 证明也很简单, 假设我们从第 i 位开始选择了一个数 A, 并且这个数 A 保持到了循环终止, 那么: |
| 36 | +
|
| 37 | + 我们知道, 第 nums[i..n] 中, A 是主元素, nums[0..i] 中, 有一个数 B 出现了一半的次数 |
| 38 | +
|
| 39 | + 假如 A = B, 那么 A 出现了大于一半的次数, A 一定是主元素 |
| 40 | +
|
| 41 | + 假如 A != B, 且主元素不是 A, 那么 B 包括其他任何数在整个数组中出现的次数一定不到一半(因为 B 包括其他任何数 |
| 42 | + 在前半部分**至多**出现一半, 而在后半部分不到一半), 因此不存在主元素, 这与题目给定的"一定存在主元素"矛盾, 因此 |
| 43 | + A 一定是主元素 |
| 44 | + */ |
| 45 | +
|
| 46 | +impl Solution { |
| 47 | + pub fn majority_element(nums: Vec<i32>) -> i32 { |
| 48 | + let mut count = 0; |
| 49 | + let mut candidate = 0; |
| 50 | + for &num in nums.iter() { |
| 51 | + if count == 0 { |
| 52 | + candidate = num; |
| 53 | + } |
| 54 | + count += if num == candidate { 1 } else { -1 }; |
| 55 | + } |
| 56 | + candidate |
| 57 | + } |
| 58 | +} |
| 59 | +
|
| 60 | +// submission codes end |
| 61 | +
|
| 62 | +#[cfg(test)] |
| 63 | +mod tests { |
| 64 | + use super::*; |
| 65 | +
|
| 66 | + #[test] |
| 67 | + fn test_169() { |
| 68 | + assert_eq!(Solution::majority_element(vec![2,2,1,1,1,2,2]), 2); |
| 69 | + } |
| 70 | +} |
0 commit comments