Skip to content

Commit c359254

Browse files
authored
Merge pull request neetcode-gh#1990 from josuebrunel/feat/380-insert-delete-getrandom.go
Feat/380 insert delete getrandom.go
2 parents 9fdbcd2 + a619f87 commit c359254

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

go/0380-insert-delete-getrandom.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy