class RandomizedSet {
private Map<Integer, Integer> map;
private List<Integer> list;
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
}
public boolean insert(int val) {
if (map.containsKey(val)) {
return false;
}
list.add(val);
map.put(val, list.size() - 1);
return true;
}
public boolean remove(int val) {
if (!map.containsKey(val)) {
return false;
}
int index = map.get(val);
if (index == list.size() - 1) {
map.remove(val);
list.remove(index);
return true;
}
map.remove(val);
int tmp = list.get(list.size() - 1);
list.remove(list.size() - 1);
list.set(index, tmp);
map.put(tmp, index);
return true;
}
public int getRandom() {
Random random = new Random();
int index = random.nextInt(list.size());
return list.get(index);
}
}
/**
* 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();
*/