Welcome to Subscribe On Youtube
381. Insert Delete GetRandom O(1) - Duplicates allowed
Description
RandomizedCollection
is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.
Implement the RandomizedCollection
class:
RandomizedCollection()
Initializes the emptyRandomizedCollection
object.bool insert(int val)
Inserts an itemval
into the multiset, even if the item is already present. Returnstrue
if the item is not present,false
otherwise.bool remove(int val)
Removes an itemval
from the multiset if present. Returnstrue
if the item is present,false
otherwise. Note that ifval
has multiple occurrences in the multiset, we only remove one of them.int getRandom()
Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains.
You must implement the functions of the class such that each function works on average O(1)
time complexity.
Note: The test cases are generated such that getRandom
will only be called if there is at least one item in the RandomizedCollection
.
Example 1:
Input ["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []] Output [null, true, false, true, 2, true, 1] Explanation RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains [1,1]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains [1,1,2]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3, or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains [1,2]. randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.
Constraints:
-231 <= val <= 231 - 1
- At most
2 * 105
calls in total will be made toinsert
,remove
, andgetRandom
. - There will be at least one element in the data structure when
getRandom
is called.
Solutions
For the insert()
function, we add the position of the number to be inserted in nums to the end of the m[val]
array, and then add val to the end of the array nums.
We judge whether there is a duplication as long as the m[val]
array has only one value of val just added or there are multiple values.
The remove()
function is the difficulty of this problem. First, let’s see if there is a val in the HashMap, and if not, return false directly.
Then we take the tail element of nums, and update the last position in the position array of the tail element HashMap to the tail element of m[val]
, so that we can delete the tail element of m[val]
. If m[val]
there is only one element, then we delete this mapping directly. Then delete the tail element in the nums array and assign the tail element to the position of val.
- Note that we need to use a heap instead of a normal vector array when building the mapping of HashMap
We use the priority queue to automatically sort all the coordinates of the same number, and move out the coordinates of the largest position each time.
-
class RandomizedCollection { private Map<Integer, Set<Integer>> m; private List<Integer> l; private Random rnd; /** Initialize your data structure here. */ public RandomizedCollection() { m = new HashMap<>(); l = new ArrayList<>(); rnd = new Random(); } /** * Inserts a value to the collection. Returns true if the collection did not already contain * the specified element. */ public boolean insert(int val) { m.computeIfAbsent(val, k -> new HashSet<>()).add(l.size()); l.add(val); return m.get(val).size() == 1; } /** * Removes a value from the collection. Returns true if the collection contained the specified * element. */ public boolean remove(int val) { if (!m.containsKey(val)) { return false; } Set<Integer> idxSet = m.get(val); int idx = idxSet.iterator().next(); int lastIdx = l.size() - 1; l.set(idx, l.get(lastIdx)); idxSet.remove(idx); Set<Integer> lastIdxSet = m.get(l.get(lastIdx)); lastIdxSet.remove(lastIdx); if (idx < lastIdx) { lastIdxSet.add(idx); } if (idxSet.isEmpty()) { m.remove(val); } l.remove(lastIdx); return true; } /** Get a random element from the collection. */ public int getRandom() { int size = l.size(); return size == 0 ? -1 : l.get(rnd.nextInt(size)); } } /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection obj = new RandomizedCollection(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
-
from collections import defaultdict from random import choice class RandomizedCollection: # official solution def __init__(self): """ Initialize your data structure here. """ self.lst = [] self.dict = defaultdict(set) # change from 381 (with no duplicates) def insert(self, val: int) -> bool: """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. """ self.dict[val].add(len(self.lst)) self.lst.append(val) return len(self.dict[val]) == 1 ''' >>> a = set([1,1,2,3]) >>> a {1, 2, 3} >>> a.pop() 1 >>> a {2, 3} ''' def remove(self, val: int) -> bool: """ Removes a value from the collection. Returns true if the collection contained the specified element. """ if not self.dict[val]: return False remove_index, last_val = self.dict[val].pop(), self.lst[-1] # pop() on a set self.lst[remove_index] = last_val self.dict[last_val].add(remove_index) self.dict[last_val].discard(len(self.lst) - 1) self.lst.pop() return True def getRandom(self) -> int: """ Get a random element from the collection. """ return choice(self.lst) # 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()