1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/rs/insert-delete-getrandom-o1.rs

40 lines
842 B
Rust
Raw Normal View History

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();
*/