10.31 每日一题 381. O(1) 时间插入、删除和获取随机元素 - 允许重复

该博客介绍了如何设计一个数据结构,该结构在平均时间复杂度为O(1)的情况下支持插入、删除和随机获取元素的操作。通过使用哈希表来跟踪元素数量,实现了在集合中快速插入、删除元素,并能按元素出现概率返回随机元素。示例展示了插入、删除和获取随机元素的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。

注意: 允许出现重复元素。

  1. insert(val):向集合中插入元素 val
  2. remove(val):当 val存在时,从集合中移除一个val
  3. getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。

示例:

// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();

// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);

// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);

// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
collection.insert(2);

// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();

// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
collection.remove(1);

// getRandom 应有相同概率返回 1 和 2 。
collection.getRandom();

通过次数9,248 | 提交次数21,609

代码实现

class RandomizedCollection:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.sets = {}
        self.nums = 0

    def insert(self, val: int) -> bool:
        """
        Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
        """
        if val in self.sets:
            self.sets[val]+=1
        else:
            self.sets[val] = 1
        self.nums+=1
        return self.sets[val]==1

    def remove(self, val: int) -> bool:
        """
        Removes a value from the collection. Returns true if the collection contained the specified element.
        """
        if val in self.sets:
            self.sets[val] -= 1
            self.nums-=1
            if self.sets[val]==0:
                del self.sets[val]
            return True
        return False

    def getRandom(self) -> int:
        """
        Get a random element from the collection.
        """
        randnum = random.randint(1, self.nums)
        idx = 0
        for k,v in self.sets.items():
            if idx+v>=randnum:
                return k
            else:
                idx+=v

# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jhaos

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值