leetcode381 o(1)时间数据操作

讲道理,我看了很多的答案,很多宣称是o(1)的结果都不是,包括百度首页的那几个哥们。

好吧 首先这个题是基于380的你们可以去看看这篇文章,这个380看懂了再回来看我的,我就基于他的基础讲了。

具体不同的是,这里的数据有重复,那么我们需要维护我们的每个元素在数组中的位置。刚开始我用list去维护,打死也做不到o(1)

后面改用集合就没问题了,这就是真正的O(1)了。

直接上代码吧

class RandomizedCollection:
    import random
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.hash = {}  #用来维护数值的位置信息
        self.data = []  #用来存储数值,最后用来生成随机数用的
        self.index = 0  #表示当前需要插入的数字的index
        self.length = 0 #表示当前数组的长度
        

    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 self.index==self.length:
            self.data.append(val)
            self.length+=1
        else:
            self.data[self.index] = val
        self.index+=1
        if val in self.hash:
            self.hash[val].add(self.index-1)
            return False
        else:
            self.hash[val]={self.index-1}  #注意这里是维护成了集合而不是列表,这很关键
            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.hash:
            val_index = self.hash[val].pop()
            if not self.hash[val]:
                self.hash.pop(val)
            if self.index-val_index!=1:
                self.data[val_index] = self.data[self.index-1]
                self.hash[self.data[val_index]].remove(self.index-1) #正因为这里是集合,所以remove的时间复杂度是o(1)这是list做不到的
                self.hash[self.data[val_index]].add(val_index)
            self.index-=1
            return True
        return False
        

    def getRandom(self):
        """
        Get a random element from the collection.
        :rtype: int
        """
        return self.data[random.randint(0,self.index-1)]


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值