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))]
}
相关推荐
木井巳4 小时前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
码途行者4 小时前
每天10分钟学Go:第23课 协程(goroutine)
开发语言·后端·golang
利威尔xu7 小时前
2026-11-25-Go-panic-recover面试
面试·golang
码途行者7 小时前
每天10分钟学Go:第24课 通道-协程之间的传送带
开发语言·后端·golang
Navigator_Z7 小时前
LeetCode //C - 1326. Minimum Number of Taps to Open to Water a Garden
c语言·算法·leetcode
Rain的Java大神之路20 小时前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
让我们一起加油好吗2 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
Rain的Java大神之路2 天前
LeetCode 42「接雨水」:面试官百出不厌的题,一文讲透从暴力到双指针 O(1)
java·后端·leetcode
codeejun3 天前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
码途行者4 天前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang