8000 src/bin/insert-delete-getrandom-o1.rs · bestgopher/leetcode@3161d71 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3161d71

Browse files
committed
src/bin/insert-delete-getrandom-o1.rs
1 parent 4194323 commit 3161d71

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/bin/insert-delete-getrandom-o1.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
fn main() {}
2+
3+
struct Solution;
4+
5+
/**
6+
* Your RandomizedSet object will be instantiated and called as such:
7+
* let obj = RandomizedSet::new();
8+
* let ret_1: bool = obj.insert(val);
9+
* let ret_2: bool = obj.remove(val);
10+
* let ret_3: i32 = obj.get_random();
11+
*/
12+
struct RandomizedSet {
13+
set: std::cell::RefCell<std::collections::HashSet<i32>>,
14+
}
15+
16+
17+
/**
18+
* `&self` means the method takes an immutable reference.
19+
* If you need a mutable reference, change it to `&mut self` instead.
20+
*/
21+
impl RandomizedSet {
22+
/** Initialize your data structure here. */
23+
fn new() -> Self {
24+
Self {
25+
set: std::cell::RefCell::new(std::collections::HashSet::default()),
26+
}
27+
}
28+
29+
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
30+
fn insert(&self, val: i32) -> bool {
31+
self.set.borrow_mut().insert(val)
32+
}
33+
34+
/** Removes a value from the set. Returns true if the set contained the specified element. */
35+
fn remove(&self, val: i32) -> bool {
36+
self.set.borrow_mut().remove(&val)
37+
}
38+
39+
/** Get a random element from the set. */
40+
fn get_random(&self) -> i32 {
41+
use rand::Rng;
42+
let mut rng = rand::thread_rng();
43+
let s = rng.gen_range(0..self.set.borrow().len());
44+
for (i, v) in self.set.borrow().iter().enumerate() {
45+
if i == s {
46+
return *v;
47+
}
48+
}
49+
50+
0
51+
}
52+
}

0 commit comments

Comments
 (0)
0