1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

rs: add «169. Majority Element»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-02-12 20:38:45 +01:00
parent 530181cf50
commit 6fa8544de7
Signed by: mfocko
GPG key ID: 7C47D46246790496

44
rs/majority-element.rs Normal file
View 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);
}
}