File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments