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))]
}
相关推荐
.普通人1 小时前
c语言--力扣简单题目(链表的中间节点)讲解
c语言·leetcode·链表
蒙娜丽宁1 小时前
Go语言错误处理详解
ios·golang·go·xcode·go1.19
__AtYou__2 小时前
Golang | Leetcode Golang题解之第412题Fizz Buzz
leetcode·golang·题解
源代码•宸4 小时前
Leetcode—322. 零钱兑换【中等】(memset(dp,0x3f, sizeof(dp))
c++·算法·leetcode·职场和发展·dp
白总Server5 小时前
php语言基本语法
开发语言·ide·后端·golang·rust·github·php
戊子仲秋8 小时前
【LeetCode】每日一题 2024_9_13 预算内的最多机器人数目(滑动窗口、单调队列)
算法·leetcode
敲代码不忘补水9 小时前
二十种编程语言庆祝中秋节
java·javascript·python·golang·html
Chase-Hart10 小时前
【每日一题】LeetCode 7.整数反转(数学)
java·数据结构·算法·leetcode·eclipse
MogulNemenis10 小时前
力扣100题——贪心算法
算法·leetcode·贪心算法
Rivieres14 小时前
算法入门-贪心1
java·算法·leetcode·推荐算法