Day12-Insert Delete GetRandom O(1)(medium)
问题描述:
Design a data structure that supports all following operations in average O(1) time.
insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
实现一个集合的数据结构,这个集合由三个函数组成,插入,删除,返回随机数。每一个操作要求我们的时间复杂度在O(1)
Example:
// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);
// Returns false as 2 does not exist in the set.
randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);
// 2 was already in the set, so return false.
randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();
解法:
因为要求用O(1)的时间复杂度,所以想到用字典存储插入的值,在返回随机数的那个函数,我们可以用random来返回随机数。虽然不知道这样是不是就违反了O(1)的要求。。
import random
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.random = {}
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val not in self.random:
self.random[val] = 0
return True
else:
return False
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val in self.random:
self.random.pop(val)
return True
else:
return False
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
if self.random:
return random.sample(self.random.keys(),1)[0]
else:
return False
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
解法:
上面用random随机数应该还是不能满足题中要求,虽然是通过了。但是看了网上的一些解析。认为下面这种解法才是想考我们的。
用一个hashtable和数组分别存储数字和对应位置的映射以及数字。
插入操作,先看字典中有无这个值(时间复杂度为O(1)),如果没有,就把这个数字插入到数组末尾,并且将位置和值存入字典。
删除操作同样先看有无这个值,有的话,字典中的值可以用O(1)删除,但是数组就不行了,这时我们可以得到字典中该值的位置,然后将其与数组中最后一个元素交换,再删除最后一个元素即可。
取随机数,就根据数组的长度随机取一个下标,返回其值就可以了。
import random
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.random_dict = {}
self.random_list = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val not in self.random_dict:
self.random_list.append(val)
self.random_dict[val] = len(self.random_list) - 1
return True
else:
return False
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val in self.random_dict:
i = self.random_dict[val]
self.random_dict[self.random_list[-1]] = i
self.random_list[i],self.random_list[-1] = self.random_list[-1],self.random_list[i]
self.random_dict.pop(val)
self.random_list.pop()
return True
else:
return False
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
if self.random_list:
return random.choice(self.random_list)
else:
return False
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()