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))]
}
相关推荐
hn小菜鸡1 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
亮亮爱刷题9 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
大模型铲屎官9 天前
【Go语言-Day 7】循环控制全解析:从 for 基础到 for-range 遍历与高级控制
开发语言·人工智能·后端·golang·大模型·go语言·循环控制
zmuy9 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
chao_7899 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king9 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法
呆呆的小鳄鱼10 天前
leetcode:746. 使用最小花费爬楼梯
算法·leetcode·职场和发展
YuTaoShao10 天前
【LeetCode 热题 100】42. 接雨水——(解法一)前后缀分解
java·算法·leetcode·职场和发展
mxpan10 天前
深入探究 Go 语言中使用 SQLite 数据库
数据库·golang·sqlite
YuforiaCode10 天前
(LeetCode 面试经典 150 题) 27.移除元素
算法·leetcode·面试