File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ import "math/rand"
2
+
3
+ type RandomizedSet struct {
4
+ hash map [int ]int
5
+ array []int
6
+ length int
7
+ }
8
+
9
+ func Constructor () RandomizedSet {
10
+ return RandomizedSet {
11
+ hash : make (map [int ]int ),
12
+ array : []int {},
13
+ length : 0 ,
14
+ }
15
+ }
16
+
17
+ func (this * RandomizedSet ) Insert (val int ) bool {
18
+ if _ , ok := this .hash [val ]; ok {
19
+ return false
20
+ }
21
+ this .array = append (this .array , val )
22
+ this .hash [val ] = len (this .array ) - 1
23
+ this .length ++
24
+ return true
25
+ }
26
+
27
+ func (this * RandomizedSet ) Remove (val int ) bool {
28
+ idx , ok := this .hash [val ]
29
+ if ! ok {
30
+ return false
31
+ }
32
+ last := this .array [this .length - 1 ]
33
+ this .array [idx ] = last
34
+ this .hash [last ] = idx
35
+ this .array = this .array [:len (this .array )- 1 ]
36
+ delete (this .hash , val )
37
+ this .length --
38
+ return true
39
+ }
40
+
41
+ func (this * RandomizedSet ) GetRandom () int {
42
+ return this .array [rand .Intn (this .length )]
43
+ }
You can’t perform that action at this time.
0 commit comments