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))]
}
相关推荐
无聊的小坏坏12 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
浮灯Foden15 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
执子手 吹散苍茫茫烟波16 小时前
leetcode415. 字符串相加
java·leetcode·字符串
执子手 吹散苍茫茫烟波18 小时前
LCR 076. 数组中的第 K 个最大元素
leetcode·排序算法
山顶风景独好19 小时前
【Leetcode】随笔
数据结构·算法·leetcode
·白小白1 天前
力扣(LeetCode) ——100. 相同的树(C语言)
c语言·算法·leetcode
墩墩同学1 天前
【LeetCode题解】LeetCode 74. 搜索二维矩阵
算法·leetcode·二分查找
1白天的黑夜11 天前
前缀和-560.和为k的子数组-力扣(LeetCode)
c++·leetcode·前缀和
m0_672813771 天前
Leetcode-3427变长子数组求和
leetcode
崎岖Qiu1 天前
leetcode100.相同的树(递归练习题)
算法·leetcode·二叉树·力扣·递归