Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Feat/380 insert delete getrandom.go #1990

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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)]
}