1
+ var RandomizedSet = function ( ) {
2
+ this . _data = [ ] ;
3
+ this . _flatData = [ ] ;
4
+ } ;
5
+
6
+ RandomizedSet . prototype . hash = function ( val ) {
7
+ return val % 1e5 ;
8
+ }
9
+
10
+ RandomizedSet . prototype . insert = function ( val ) {
11
+ const hash = this . hash ( val ) ;
12
+ let basket = this . _data [ hash ] ;
13
+
14
+ for ( let i = 0 ; i < basket ?. length ; i ++ ) {
15
+ if ( basket [ i ] [ 0 ] === val ) { return false ; }
16
+ }
17
+
18
+ if ( ! basket ) {
19
+ this . _data [ hash ] = [ [ val , this . _flatData . length ] ] ;
20
+ } else {
21
+ this . _data [ hash ] . push ( [ val , this . _flatData . length ] ) ;
22
+ }
23
+ this . _flatData . push ( val ) ;
24
+ return true ;
25
+ } ;
26
+
27
+ RandomizedSet . prototype . remove = function ( val ) {
28
+ const hash = this . hash ( val ) ;
29
+ let basket = this . _data [ hash ] ;
30
+ if ( ! basket ) { return false ; }
31
+ for ( let i = 0 ; i < basket . length ; i ++ ) {
32
+ const currBasket = basket [ i ] ;
33
+ if ( currBasket [ 0 ] === val ) {
34
+ const idxInFlat = currBasket [ 1 ] ;
35
+ const reassignedValueInFlat = del ( this . _flatData , idxInFlat ) ;
36
+ // Write new address in _data if needed
37
+ if ( reassignedValueInFlat ) {
38
+ this . _data [ this . hash ( reassignedValueInFlat ) ] . forEach ( item => {
39
+ if ( item [ 0 ] === reassignedValueInFlat ) {
40
+ item [ 1 ] = idxInFlat ;
41
+ return ; // from forEach
42
+ }
43
+ } ) ;
44
+ }
45
+ // Delete from _data
46
+ del ( basket , i ) ;
47
+ return true ;
48
+ }
49
+ }
50
+ return false ;
51
+ } ;
52
+
53
+ RandomizedSet . prototype . getRandom = function ( ) {
54
+ return this . _flatData [ getRandomInt ( 0 , this . _flatData . length - 1 ) ] ;
55
+ } ;
56
+
57
+ function getRandomInt ( min , max ) {
58
+ min = Math . ceil ( min ) ;
59
+ max = Math . floor ( max ) ;
60
+ return Math . floor ( Math . random ( ) * ( max - min + 1 ) ) + min ;
61
+ }
62
+
63
+ function del ( arr , idx ) {
64
+ if ( ! arr . length ) { return null ; }
65
+ if ( idx === arr . length - 1 ) { arr . pop ( ) ; return null ; }
66
+ arr [ idx ] = arr . pop ( ) ;
67
+ return arr [ idx ] ;
68
+ }
0 commit comments