diff --git a/rs/majority-element.rs b/rs/majority-element.rs new file mode 100644 index 0000000..a75f71d --- /dev/null +++ b/rs/majority-element.rs @@ -0,0 +1,44 @@ +use rand::distributions::{Distribution, Uniform}; + +struct Solution {} +impl Solution { + pub fn majority_element(mut nums: Vec) -> i32 { + let threshold = nums.len() >> 1; + + let distribution = Uniform::new(0, nums.len()); + let mut rng = rand::thread_rng(); + loop { + let sample = nums[distribution.sample(&mut rng)]; + println!("Picking sample: {}", sample); + if sample == i32::MIN { + continue; + } + + let mut counter = 0; + for x in &mut nums { + if *x == sample { + counter += 1; + *x = i32::MIN; + } + + if counter > threshold { + return sample; + } + } + } + } +} + +fn main() { + assert_eq!(Solution::majority_element(vec![3, 2, 3]), 3); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tle1() { + assert_eq!(Solution::majority_element(vec![3, 2, 3]), 3); + } +}