leetcode之Insert Delete GetRandom O(1) - Duplicates allowed

本文介绍了一个使用Python列表实现的随机集合类,该类支持插入、删除元素及获取随机元素的功能。虽然作者指出了一些操作的时间复杂度可能为O(n),但整体上提供了一种简单的方法来实现这些功能。

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

还是用的list来解决。

import random
class RandomizedCollection(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.list1 = []

    def insert(self, val):
        """
        Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
        :type val: int
        :rtype: bool
        """
        if val in self.list1:
            self.list1.append(val)
            return False
        else:
            self.list1.append(val)
            return True


    def remove(self, val):
        """
        Removes a value from the collection. Returns true if the collection contained the specified element.
        :type val: int
        :rtype: bool
        """
        if val in self.list1:
            self.list1.remove(val)
            return True
        else:
            return False


    def getRandom(self):
        """
        Get a random element from the collection.
        :rtype: int
        """
        return random.choice(self.list1)

不过看到了题目写的是O(1),感觉很多都是O(n)啊,不过不知道怎么才能O(1),倒是也给过了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值