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))]
}
相关推荐
Billlly3 小时前
ABC 453 个人题解
算法·题解·atcoder
Dontla3 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
铁东博客4 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
小白菜又菜5 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
wechat_Neal7 小时前
Golang的车载应用场景
开发语言·后端·golang
摸个小yu9 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
Wenweno0o9 小时前
Eino-Graph 实战详解
golang·智能体·eino
skywalker_1110 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
生信研究猿11 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
XWalnut11 小时前
LeetCode刷题 day9
java·算法·leetcode