Skip to content

Commit

Permalink
Create 0380-insert-delete-getrandom.go
Browse files Browse the repository at this point in the history
  • Loading branch information
josuebrunel committed Jan 11, 2023
1 parent 29fb6f4 commit a619f87
Showing 1 changed file with 43 additions and 0 deletions.
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)]
}

0 comments on commit a619f87

Please sign in to comment.