rs: add «169. Majority Element»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
530181cf50
commit
6fa8544de7
1 changed files with 44 additions and 0 deletions
44
rs/majority-element.rs
Normal file
44
rs/majority-element.rs
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue