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

题目:

题解:

Go 复制代码
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 int
    for id := range ids {
        i = id
        break
    }
    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))]
}
相关推荐
做怪小疯子27 分钟前
LeetCode 热题 100——二叉树——二叉树的最大深度
算法·leetcode·职场和发展
Maỿbe36 分钟前
暴打力扣之优先级队列(堆)
算法·leetcode·职场和发展
Swift社区36 分钟前
LeetCode 438 - 找到字符串中所有字母异位词
算法·leetcode·职场和发展
学学学无无止境43 分钟前
力扣-位1的个数
leetcode
别学LeetCode1 小时前
#leetcode# 1
leetcode
b***65321 小时前
Go-Gin Web 框架完整教程
前端·golang·gin
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2025.11.30 题目:1590.使数组和能被 P 整除
笔记·算法·leetcode
皖南大花猪1 小时前
Go 项目中使用 Casbin 实现 RBAC 权限管理完整教程
开发语言·后端·golang·rbac·casbin
源代码•宸1 小时前
GoLang写一个火星漫游行动
开发语言·经验分享·后端·golang
le serein —f2 小时前
用go实现-回文链表
算法·leetcode·golang