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))]
}
相关推荐
TracyCoder1231 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
放荡不羁的野指针2 小时前
leetcode150题-滑动窗口
数据结构·算法·leetcode
女王大人万岁3 小时前
Go标准库 io与os库详解
服务器·开发语言·后端·golang
TracyCoder1233 小时前
LeetCode Hot100(13/100)——238. 除了自身以外数组的乘积
算法·leetcode
Anastasiozzzz3 小时前
LeetCode Hot100 215. 数组中的第K个最大元素
数据结构·算法·leetcode
让我上个超影吧3 小时前
【力扣76】最小覆盖子串
算法·leetcode·职场和发展
求梦8205 小时前
【力扣hot100题】合并两个有序链表(22)
算法·leetcode·链表
女王大人万岁5 小时前
Go语言time库核心用法与实战避坑
服务器·开发语言·后端·golang
踩坑记录5 小时前
leetcode hot100 21.合并两个有序链表 链表 easy
leetcode
IT_Octopus5 小时前
力扣热题100 20. 有效的括号
算法·leetcode