Design a data structure that supports all following operations in average O(1) time.
Note: Duplicate elements are allowed.
insert(val)
: Inserts an item val to the collection.remove(val)
: Removes an item val from the collection if present.getRandom
: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.
Example:
// Init an empty collection. RandomizedCollection collection = new RandomizedCollection(); // Inserts 1 to the collection. Returns true as the collection did not contain 1. collection.insert(1); // Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1]. collection.insert(1); // Inserts 2 to the collection, returns true. Collection now contains [1,1,2]. collection.insert(2); // getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3. collection.getRandom(); // Removes 1 from the collection, returns true. Collection now contains [1,2]. collection.remove(1); // getRandom should return 1 and 2 both equally likely. collection.getRandom();
题目 提供O(1)复杂度的接口:1.添加一个数字;2.删除一个数字;3.随机返回一个数字。
还是利用HashMap操作的O(1)属性。使用HashMap + arr 解决,在arr中删除时使用尾部填充的方式达到O(1)。代码如下:
class RandomizedCollection(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.indexs = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
ret = True
self.nums.append(val)
if val in self.indexs:
ret = False
self.indexs.get(val).add(len(self.nums) - 1)
else:
self.indexs[val] = set([len(self.nums) - 1])
return ret
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.indexs:
return False
lastValue = self.nums[-1]
removeIndex = self.indexs[val].pop()
if len(self.indexs[val]) == 0:
self.indexs.pop(val)
if removeIndex != len(self.nums) - 1:
self.indexs[lastValue].remove(len(self.nums)-1)
self.indexs[lastValue].add(removeIndex)
self.nums[removeIndex] = lastValue
self.nums.pop()
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.nums)
# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()