12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- type pair struct {
- _1 int
- _2 *list.Element
- }
- type RandomizedCollection struct {
- nums []pair
- size int
- pos map[int]*list.List
- }
- func Constructor() RandomizedCollection {
- return RandomizedCollection{pos: make(map[int]*list.List)}
- }
- func (this *RandomizedCollection) Insert(val int) bool {
- li, ok := this.pos[val]
- if !ok {
- li = list.New()
- this.pos[val] = li
- }
- ele := li.PushBack(this.size)
- this.nums = append(this.nums, pair{val, ele})
- this.size++
- return !ok
- }
- func (this *RandomizedCollection) Remove(val int) bool {
- li, ok := this.pos[val]
- if !ok {
- return false
- }
- idx := li.Remove(li.Front()).(int)
- this.size--
- this.nums[idx] = this.nums[this.size]
- this.nums[idx]._2.Value = idx
- this.nums = this.nums[:this.size]
- if li.Len() == 0 {
- delete(this.pos, val)
- }
- return true
- }
- func (this *RandomizedCollection) GetRandom() int {
- return this.nums[rand.Intn(this.size)]._1
- }
|