381. Insert Delete GetRandom O(1) - Duplicates allowed
Design a data structure that supports all following operations inaverage 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:
Thoughts:
nums: data lsit
indiecs: index reverse mapping: <val, i>
for add: check key is in the indices list set. if not put a new set in to val: <val, new set>; add i as current nums.size(), then add value to data array nums.
for remove: for check if the val is a valid key: if it is, retrieve the next index value for the val as iterator.next(), remove the index value from val entry. Then i is not at the end of the nums. Then fill the last element to the ith position in the nums list:
retrieve the value from the last element in nums as "last"
updating last's position entry record in set by first removing old index value then add value of position to be filled to the set
remove the last element from the data nums.
check the set in val becomes empty, if it is, remove the set entry in map.
Code: java
Last updated
Was this helpful?