1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-20 01:56:57 +02:00

rs: add “Insert Delete GetRandom O(1)”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-01-16 13:47:47 +01:00
parent 176d59fd1f
commit f526fbd364
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,39 @@
use rand::prelude::IteratorRandom;
use std::collections::HashSet;
struct RandomizedSet {
nums: HashSet<i32>,
}
impl RandomizedSet {
fn new() -> Self {
Self {
nums: HashSet::new(),
}
}
fn insert(&mut self, val: i32) -> bool {
self.nums.insert(val)
}
fn remove(&mut self, val: i32) -> bool {
self.nums.remove(&val)
}
fn get_random(&self) -> i32 {
let mut rng = rand::thread_rng();
*self
.nums
.iter()
.choose(&mut rng)
.expect("at least one number is in the set")
}
}
/*
* Your RandomizedSet object will be instantiated and called as such:
* let obj = RandomizedSet::new();
* let ret_1: bool = obj.insert(val);
* let ret_2: bool = obj.remove(val);
* let ret_3: i32 = obj.get_random();
*/