Skip to content

Commit

Permalink
leetcode: Add method 2 to 0169
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed May 21, 2024
1 parent a4f1fc8 commit 5f32a01
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion src/leetcode/0169.majority-element/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,39 @@ pub fn majority_element1(nums: Vec<i32>) -> i32 {
nums[nums.len() / 2]
}

// 摩尔投票法
pub fn majority_element2(nums: Vec<i32>) -> i32 {
let mut major: i32 = 0;
let mut count: usize = 0;
for &num in &nums {
if count == 0 {
// 如果 count 为 0, 把当前数作为 major
major = num;
} else if num == major {
// 如果当前整数与 major 相等, 计数就加 1
count += 1;
} else {
// 如果当前整数与 major 不相等, 计数减 1
count -= 1;
}
}

// 检验是否真的超过一半
let mut check_count: usize = 0;
for &num in &nums {
if num == major {
check_count += 1;
}
}

if check_count * 2 > nums.len() {
major
} else {
// 如果没有超过一半, 就返回 -1
-1
}
}

pub type SolutionFn = fn(Vec<i32>) -> i32;

fn check_solution(func: SolutionFn) {
Expand All @@ -23,14 +56,20 @@ fn check_solution(func: SolutionFn) {

fn main() {
check_solution(majority_element1);
check_solution(majority_element2);
}

#[cfg(test)]
mod tests {
use super::{check_solution, majority_element1};
use super::{check_solution, majority_element1, majority_element2};

#[test]
fn test_majority_element1() {
check_solution(majority_element1);
}

#[test]
fn test_majority_element2() {
check_solution(majority_element2);
}
}

0 comments on commit 5f32a01

Please sign in to comment.