Map<Integer, Integer> map;
/** Initialize your data structure here. */
nums = new ArrayList<>();
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if (map.containsKey(val)) {
map.put(val, nums.size());
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (!map.containsKey(val)) {
int index = map.get(val);
if (index < nums.size() - 1) {
int lastNum = nums.get(nums.size() - 1);
nums.set(index, lastNum);
nums.remove(nums.size() - 1);
/** Get a random element from the set. */
return nums.get(rand.nextInt(nums.size()));
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();