rs: add “Insert Delete GetRandom O(1)”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
176d59fd1f
commit
f526fbd364
1 changed files with 39 additions and 0 deletions
39
rs/insert-delete-getrandom-o1.rs
Normal file
39
rs/insert-delete-getrandom-o1.rs
Normal 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();
|
||||||
|
*/
|
Loading…
Reference in a new issue