- Insert Delete GetRandom O(1)
Design a data structure that supports all following operations in average O(1) time.
LC 380
- 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.
import random
class RandomizedSet:
def __init__(self):
self.num = []
self.pos = {}
"""
@param: val: a value to the set
@return: true if the set did not already contain the specified element or false
"""
def insert(self, val):
if val in self.pos:
return False
self.pos[val] = len(self.num)
self.num.append(val)
return True
"""
@param: val: a value from the set
@return: true if the set contained the specified element or false
"""
def remove(self, val):
if val in self.pos:
idx, last = self.pos[val], self.num[-1]
# val is replaced by the last element of self.num
# while all others unchanged
self.pos[last] = idx
self.num.pop
del self.pos[val] # or self.pos.pop(val, 0)
return True
return False
"""
@return: Get a random element from the set
"""
def getRandom(self):
return self.num[random.randint(0, len(self.num) - 1)]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param = obj.insert(val)
# param = obj.remove(val)
# param = obj.getRandom()
- Time
O(1)
- Space
O(n)
Note:
-
One key is to have:
onenum
list (for choosing random number)
onepos
set (forO(1) look up time
). -
Another key point for me is in
remove(val)
. That is I can switch the last one with the removed one. As a result, other numbers' positions are unchanged. -
remember usage of
random
(inclusive)
import random
random_num = random.randint(0, len(list) - 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();
网友评论