欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > Golang | Leetcode Golang题解之第381题O(1)时间插入、删除和获取随机元素-允许重复

Golang | Leetcode Golang题解之第381题O(1)时间插入、删除和获取随机元素-允许重复

2024/10/23 19:34:23 来源:https://blog.csdn.net/weixin_66442839/article/details/141654649  浏览:    关键词:Golang | Leetcode Golang题解之第381题O(1)时间插入、删除和获取随机元素-允许重复

题目:

题解:

type RandomizedCollection struct {idx  map[int]map[int]struct{}nums []int
}/** Initialize your data structure here. */
func Constructor() RandomizedCollection {return RandomizedCollection{idx: map[int]map[int]struct{}{},}
}/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
func (r *RandomizedCollection) Insert(val int) bool {ids, has := r.idx[val]if !has {ids = map[int]struct{}{}r.idx[val] = ids}ids[len(r.nums)] = struct{}{}r.nums = append(r.nums, val)return !has
}/** Removes a value from the collection. Returns true if the collection contained the specified element. */
func (r *RandomizedCollection) Remove(val int) bool {ids, has := r.idx[val]if !has {return false}var i intfor id := range ids {i = idbreak}n := len(r.nums)r.nums[i] = r.nums[n-1]delete(ids, i)delete(r.idx[r.nums[i]], n-1)if i < n-1 {r.idx[r.nums[i]][i] = struct{}{}}if len(ids) == 0 {delete(r.idx, val)}r.nums = r.nums[:n-1]return true
}/** Get a random element from the collection. */
func (r *RandomizedCollection) GetRandom() int {return r.nums[rand.Intn(len(r.nums))]
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com