ArrayList + HashMap
Time O(1) average Space O(n)index[val] = position. remove: move the last value into val's position, update its index, remove the last slot.
insert(1), remove(2), insert(2), remove(1), insert(2), getRandom()index(map)
returned(list)
Step 1/5insert(1): 1 is new, so record its position 0 and append it. Return true.
import java.util.*;
class RandomizedSet {
private final List<Integer> vals = new ArrayList<>();
private final Map<Integer, Integer> index = new HashMap<>();
private final Random random = new Random();
public RandomizedSet() {}
public boolean insert(int val) {
if (index.containsKey(val)) return false;
index.put(val, vals.size());
vals.add(val);
return true;
}
public boolean remove(int val) {
Integer i = index.remove(val);
if (i == null) return false;
int last = vals.remove(vals.size() - 1);
if (i < vals.size()) { vals.set(i, last); index.put(last, i); }
return true;
}
public int getRandom() { return vals.get(random.nextInt(vals.size())); }
}Verdict: The standard trick.