Problem
Build a class RandomizedSet that stores distinct integers and supports three operations, each in average O(1) time:
- insert(val): add val if it is not already present. Return true if it was added, false if it was already there.
- remove(val): delete val if present. Return true if it was removed, false if it was not there.
- get_random() (getRandom in TypeScript): return a random current element, where every element is equally likely.
Example 1
s = RandomizedSet()
Example 2
- Input
- s.insert(1)
- Output
- true
Example 3
- Input
- s.remove(2)
- Output
- false
Example 4
- Input
- s.insert(2)
- Output
- true
Example 5
- Input
- s.get_random()
- Output
- 1 or 2
Example 6
- Input
- s.remove(1)
- Output
- true
Example 7
- Input
- s.get_random()
- Output
- 2
- Why
- the only element left
Constraints
-2^31 <= val <= 2^31 - 1At most 2 * 10^5 calls in total.get_random is only called when the set is not empty.