Last active
February 29, 2024 15:39
-
-
Save andyjessop/b997dd73b6cb294a0c776d35575364e5 to your computer and use it in GitHub Desktop.
An implementation of the RandomizedSet class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type RandomizedSet struct { | |
Entries map[int]bool | |
Values []int | |
Indexes map[int]int | |
} | |
func Constructor() *RandomizedSet { | |
return &RandomizedSet{Entries: make(map[int]bool), Indexes: make(map[int]int)} | |
} | |
func (this *RandomizedSet) Insert(val int) bool { | |
_, exists := this.Entries[val] | |
if exists == true { | |
return false | |
} | |
this.Entries[val] = true | |
this.Values = append(this.Values, val) | |
this.Indexes[val] = len(this.Values) - 1 | |
return true | |
} | |
func (this *RandomizedSet) Remove(val int) bool { | |
set := *this | |
_, exists := set.Entries[val] | |
if exists == false { | |
return false | |
} | |
delete(set.Entries, val) | |
index := this.Indexes[val] | |
this.Values = append(this.Values[:index], this.Values[index+1:]...) | |
delete(this.Indexes, val) | |
return true | |
} | |
func (this *RandomizedSet) GetRandom() int { | |
length := len(this.Values) | |
randomNumber := rand.Intn(length) | |
return this.Values[randomNumber] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment