File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
solution/0300-0399/0380.Insert Delete GetRandom O(1) Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ var RandomizedSet = function ( ) {
2
+ this . d = new Map ( ) ;
3
+ this . q = [ ] ;
4
+ } ;
5
+
6
+ /**
7
+ * @param {number } val
8
+ * @return {boolean }
9
+ */
10
+ RandomizedSet . prototype . insert = function ( val ) {
11
+ if ( this . d . has ( val ) ) {
12
+ return false ;
13
+ }
14
+ this . d . set ( val , this . q . length ) ;
15
+ this . q . push ( val ) ;
16
+ return true ;
17
+ } ;
18
+
19
+ /**
20
+ * @param {number } val
21
+ * @return {boolean }
22
+ */
23
+ RandomizedSet . prototype . remove = function ( val ) {
24
+ if ( ! this . d . has ( val ) ) {
25
+ return false ;
26
+ }
27
+ const i = this . d . get ( val ) ;
28
+ this . d . set ( this . q [ this . q . length - 1 ] , i ) ;
29
+ this . q [ i ] = this . q [ this . q . length - 1 ] ;
30
+ this . q . pop ( ) ;
31
+ this . d . delete ( val ) ;
32
+ return true ;
33
+ } ;
34
+
35
+ /**
36
+ * @return {number }
37
+ */
38
+ RandomizedSet . prototype . getRandom = function ( ) {
39
+ return this . q [ Math . floor ( Math . random ( ) * this . q . length ) ] ;
40
+ } ;
41
+
42
+ /**
43
+ * Your RandomizedSet object will be instantiated and called as such:
44
+ * var obj = new RandomizedSet()
45
+ * var param_1 = obj.insert(val)
46
+ * var param_2 = obj.remove(val)
47
+ * var param_3 = obj.getRandom()
48
+ */
You can’t perform that action at this time.
0 commit comments