forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0380-insert-delete-getrandom-o1.go
43 lines (38 loc) · 808 Bytes
/
0380-insert-delete-getrandom-o1.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import"math/rand"
typeRandomizedSetstruct {
hashmap[int]int
array []int
lengthint
}
funcConstructor() RandomizedSet {
returnRandomizedSet{
hash: make(map[int]int),
array: []int{},
length: 0,
}
}
func (this*RandomizedSet) Insert(valint) bool {
if_, ok:=this.hash[val]; ok {
returnfalse
}
this.array=append(this.array, val)
this.hash[val] =len(this.array) -1
this.length++
returntrue
}
func (this*RandomizedSet) Remove(valint) bool {
idx, ok:=this.hash[val]
if!ok {
returnfalse
}
last:=this.array[this.length-1]
this.array[idx] =last
this.hash[last] =idx
this.array=this.array[:len(this.array)-1]
delete(this.hash, val)
this.length--
returntrue
}
func (this*RandomizedSet) GetRandom() int {
returnthis.array[rand.Intn(this.length)]
}