LeetCode/rs/majority-element.rs

45 lines
1 KiB
Rust
Raw Permalink Normal View History

use rand::distributions::{Distribution, Uniform};
struct Solution {}
impl Solution {
pub fn majority_element(mut nums: Vec<i32>) -> 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);
}
}