😕题目描述
https://leetcode-cn.com/problems/insert-delete-getrandom-o1/
😔分析
😏答案
import "math/rand"type RandomizedSet struct {mp map[int]intsli []intlength int}func Constructor() RandomizedSet {return RandomizedSet{mp: make(map[int]int),sli: make([]int, 0),length: 0,}}func (this *RandomizedSet) Insert(val int) bool {if _, ok := this.mp[val]; ok {return false}if len(this.sli) == this.length {this.sli = append(this.sli, val)} else {this.sli[this.length] = val}this.mp[val] = this.lengththis.length++return true}func (this *RandomizedSet) Remove(val int) bool {if _, ok := this.mp[val]; !ok {return false}end := this.sli[this.length - 1]this.sli[this.length - 1], this.sli[this.mp[val]] = this.sli[this.mp[val]], this.sli[this.length - 1]this.mp[end], this.mp[val] = this.mp[val], this.mp[end]this.length--delete(this.mp, val)return true}func (this *RandomizedSet) GetRandom() int {index := rand.Int() % this.lengthreturn this.sli[index]}
