File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ use rand:: seq:: SliceRandom ;
2+ use std:: collections:: HashMap ;
3+
4+ pub struct RandomizedSet {
5+ mp : HashMap < i32 , i32 > ,
6+ arr : Vec < i32 > ,
7+ }
8+
9+ impl RandomizedSet {
10+ fn new ( ) -> Self {
11+ RandomizedSet {
12+ mp : HashMap :: new ( ) ,
13+ arr : Vec :: new ( ) ,
14+ }
15+ }
16+
17+ fn insert ( & mut self , val : i32 ) -> bool {
18+ let res = !self . mp . contains_key ( & val) ;
19+ if res {
20+ self . mp . insert ( val, self . arr . len ( ) as i32 ) ;
21+ self . arr . push ( val) ;
22+ }
23+ res
24+ }
25+ fn remove ( & mut self , val : i32 ) -> bool {
26+ let res = self . mp . contains_key ( & val) ;
27+ if res {
28+ let idx = * self . mp . get ( & val) . unwrap ( ) ;
29+ self . mp
30+ . entry ( * self . arr . last ( ) . unwrap ( ) )
31+ . and_modify ( |v| * v = idx) ;
32+ self . arr . swap_remove ( idx as usize ) ;
33+ self . mp . remove ( & val) ;
34+ }
35+ res
36+ }
37+ fn get_random ( & self ) -> i32 {
38+ * self . arr . choose ( & mut rand:: thread_rng ( ) ) . unwrap ( )
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments