讲道理,我看了很多的答案,很多宣称是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)]