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))]
}
相关推荐
alphaTao6 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1236 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi7 小时前
力扣70爬楼梯
数据结构·算法·leetcode
云和数据.ChenGuang7 小时前
Golang AI 工程师路线图:从入门到实战
开发语言·人工智能·后端·golang
报错小能手9 小时前
内存管理 垃圾回收面试题
golang
Navigator_Z1 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2081 天前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2081 天前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2081 天前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
tachibana21 天前
Go 语言里的 Context 是什么?
开发语言·后端·golang·go·语言