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))]
}
相关推荐
王老师青少年编程2 小时前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(选择题1-5)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
Bear on Toilet3 小时前
递归_二叉树_50 . 从前序与中序遍历序列构造二叉树
数据结构·算法·leetcode·深度优先·递归
追随者永远是胜利者6 小时前
(LeetCode-Hot100)62. 不同路径
java·算法·leetcode·职场和发展·go
追随者永远是胜利者6 小时前
(LeetCode-Hot100)56. 合并区间
java·算法·leetcode·职场和发展·go
追随者永远是胜利者6 小时前
(LeetCode-Hot100)55. 跳跃游戏
java·算法·leetcode·游戏·go
锅包一切7 小时前
PART17 一维动态规划
c++·学习·算法·leetcode·动态规划·力扣·刷题
We་ct10 小时前
LeetCode 226. 翻转二叉树:两种解法(递归+迭代)详解
前端·算法·leetcode·链表·typescript
追随者永远是胜利者10 小时前
(LeetCode-Hot100)64. 最小路径和
java·算法·leetcode·职场和发展·go
追随者永远是胜利者12 小时前
(LeetCode-Hot100)70. 爬楼梯
java·算法·leetcode·职场和发展·go
桂花很香,旭很美13 小时前
[7天实战入门Go语言后端] Go 后端实战踩坑与解法手册
服务器·网络·golang