题目:
实现RandomizedSet 类:
RandomizedSet()初始化RandomizedSet对象bool insert(int val)当元素val不存在时,向集合中插入该项,并返回true;否则,返回false。bool remove(int val)当元素val存在时,从集合中移除该项,并返回true;否则,返回false。int getRandom()随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。
你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1) 。
算法:
type RandomizedSet struct {
LastIndex int
List []int // 为了实现随机返回元素
Map map[int]int // insert和remove
}
func Constructor() RandomizedSet {
return RandomizedSet{
LastIndex: -1,
List: make([]int, 0),
Map: make(map[int]int),
}
}
func (this *RandomizedSet) Insert(val int) bool {
if _, ok := this.Map[val]; ok {
return false
}
if this.LastIndex == len(this.List) - 1 {
this.List = append(this.List, val)
this.LastIndex ++
} else {
this.LastIndex ++
this.List[this.LastIndex] = val
}
this.Map[val] = this.LastIndex
return true
}
func (this *RandomizedSet) Remove(val int) bool {
index, ok := this.Map[val]
if !ok {
return false
}
// 注意顺序别搞乱了,出bug
this.Map[this.List[this.LastIndex]] = index
this.List[index], this.List[this.LastIndex] = this.List[this.LastIndex], this.List[index]
this.LastIndex --
delete(this.Map, val)
// fmt.Println(*this)
return true
}
func (this *RandomizedSet) GetRandom() int {
// fmt.Println(this.List, this.LastIndex, rand.Intn(this.LastIndex + 1))
return this.List[rand.Intn(this.LastIndex + 1)]
}