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))]
}
相关推荐
lightqjx1 天前
【算法】双指针
c++·算法·leetcode·双指针
sin_hielo1 天前
leetcode 2147
数据结构·算法·leetcode
萌>__<新1 天前
力扣打卡每日一题——缺失的第一个正数
数据结构·算法·leetcode
萌>__<新1 天前
力扣打卡每日一题————零钱兑换
算法·leetcode·职场和发展
古城小栈1 天前
Golang 中 return 与 defer 的 长幼尊卑
golang
重生之后端学习1 天前
238. 除自身以外数组的乘积
java·数据结构·算法·leetcode·职场和发展·哈希算法
Learner__Q1 天前
每天五分钟:动态规划-LeetCode高频题_day2
算法·leetcode·动态规划
teamlet1 天前
Gear DNS - 一个go语言开发的小型dns系统
golang·dns·网络服务
Dream it possible!1 天前
LeetCode 面试经典 150_字典树_添加与搜索单词 - 数据结构设计(96_211_C++_中等)
c++·leetcode·面试·字典树