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))]
}
相关推荐
im_AMBER4 分钟前
Leetcode 152 被围绕的区域 | 岛屿数量
数据结构·算法·leetcode·深度优先·广度优先·图搜索算法
吕司15 分钟前
LeetCode Hot Code——最大子数组和
数据结构·算法·leetcode
XiYang-DING20 分钟前
【LeetCode】144. 二叉树的前序遍历
算法·leetcode·职场和发展
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 215. 数组中的第K个最大元素 | C++ 快速选择与堆排序题解
c++·算法·leetcode
小白菜又菜1 小时前
Leetcode 3070. Count Submatrices with Top-Left Element and Sum Less Than k
算法·leetcode·职场和发展
会编程的土豆1 小时前
【数据结构与算法】拓扑排序2
数据结构·算法·leetcode
We་ct1 小时前
LeetCode 201. 数字范围按位与:位运算高效解题指南
开发语言·前端·javascript·算法·leetcode·typescript
木子欢儿2 小时前
在 Fedora 上配置 Go 语言(Golang)开发环境
开发语言·后端·golang
yangyanping201082 小时前
Go语言学习之 Gin 生产级 flag命令行参数解析库
开发语言·golang·gin
Khsc434ka2 小时前
LeetCode-001:Python 实现哈希表求两数之和:初识哈希表
python·leetcode·散列表