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))]
}
相关推荐
坚持编程的菜鸟5 小时前
LeetCode每日一题——困于环中的机器人
c语言·算法·leetcode·机器人
Achou.Wang10 小时前
源码分析 golang bigcache 高性能无 GC 开销的缓存设计实现
开发语言·缓存·golang
Yeats_Liao12 小时前
Go语言技术与应用(二):分布式架构设计解析
开发语言·分布式·golang
蓝婴天使12 小时前
基于 React + Go + PostgreSQL + Redis 的管理系统开发框架
react.js·postgresql·golang
脚踏实地的大梦想家12 小时前
【Go】P6 Golang 基础:流程控制
开发语言·golang
QX_hao13 小时前
【Go】--数组和切片
后端·golang·restful
-睡到自然醒~13 小时前
提升应用性能:Go中的同步与异步处理
开发语言·后端·golang
只吃不吃香菜13 小时前
Go WebSocket 协程泄漏问题分析与解决方案
开发语言·websocket·golang
ChineHe13 小时前
Golang并发编程篇001_并发编程相关概念解释
开发语言·后端·golang
赴前尘15 小时前
Go 通道非阻塞发送:优雅地处理“通道已满”的场景
开发语言·后端·golang