"""
题目:
设计一个数据结构,使如下三个操作的时间复杂度都是O(1)。
insert(value):如果数据集中不包含一个数值,则把它添加到数据集中。
remove(value):如果数据中包含一个数值,则把它删除
getRandom():随机返回数据集中的一个数值,要求数据集中每个数字被返回的概率都相同。
解题思路:
添加一个数据的时间复杂度为O(1)的数据结构有:链表、哈希表、列表
删除一个数据的时间复杂度为O(1)的数据结构有:哈希表,列表删除最后一个元素的时间复杂度为O(1)
返回一个随机数值的的时间复杂度为O(1)的数据结构:列表。根据一个随机索引,然后返回索引所在位置的数据。
综上,应主要使用列表,但是需要使用哈希表提供数据的索引。在删除元素时,应把数据放在列表的最后一个位置上然后删除
"""
from random import randint
class MyData:
def __init__(self):
self.d = {}
self.t = []
self.index = 0
def insert(self,value):
if value not in self.d:
self.t.append(value)
self.d[value] = self.index
self.index += 1
def remove(self,value):
if value in self.d:
location = self.d[value]
self.t[location],self.t[-1] = self.t[-1],value
self.d[self.t[location]] = location
self.t.pop(-1)
self.d.pop(value)
self.index -=1
def get_random(self):
random_location = randint(0,self.index)
return self.t[random_location]
temp = MyData()
length = 100000
for i in range(length):
temp.insert(i)
for i in range(20):
print(temp.get_random())
for i in range(length):
temp.remove(i)
《剑指offer》面试题30:插入删除和随机访问都是O(1)的容器
最新推荐文章于 2022-03-24 21:08:46 发布