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))]
}
相关推荐
Charlie_lll1 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
滴滴答滴答答2 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
圣保罗的大教堂2 小时前
leetcode 1980. 找出不同的二进制字符串 中等
leetcode
呆萌很2 小时前
【GO】逻辑运算练习题
golang
礼拜天没时间.2 小时前
力扣热题100实战 | 第25期:K个一组翻转链表——从两两交换到K路翻转的进阶之路
java·算法·leetcode·链表·递归·链表反转·k个一组翻转链表
Swift社区3 小时前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展
再难也得平3 小时前
力扣239. 滑动窗口最大值(Java解法)
算法·leetcode·职场和发展
摩尔曼斯克的海3 小时前
力扣面试题--双指针类
python·算法·leetcode
灰色小旋风3 小时前
力扣——第7题(C++)
c++·算法·leetcode
努力学算法的蒟蒻4 小时前
day106(3.7)——leetcode面试经典150
算法·leetcode·面试