Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions go/0380-insert-delete-getrandom.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import "math/rand"

type RandomizedSet struct {
hash map[int]int
array []int
length int
}

func Constructor() RandomizedSet {
return RandomizedSet{
hash: make(map[int]int),
array: []int{},
length: 0,
}
}

func (this *RandomizedSet) Insert(val int) bool {
if _, ok := this.hash[val]; ok {
return false
}
this.array = append(this.array, val)
this.hash[val] = len(this.array) - 1
this.length++
return true
}

func (this *RandomizedSet) Remove(val int) bool {
idx, ok := this.hash[val]
if !ok {
return false
}
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--
return true
}

func (this *RandomizedSet) GetRandom() int {
return this.array[rand.Intn(this.length)]
}