Insert Delete GetRandom O(1) LeetCode solution in Java
1class RandomizedSet {2HashMap<Integer, Integer> map;3ArrayList<Integer> list;4Random rand;56public RandomizedSet() {7map = new HashMap<>();8list = new ArrayList<>();9rand = new Random();10}1112public boolean insert(int val) {13if (!map.containsKey(val)) {14map.put(val, list.size());15list.add(val);16return true;17}18return false;19}2021public boolean remove(int val) {22if (map.containsKey(val)) {23int index = map.get(val);24int last = list.get(list.size() - 1);25if (index != list.size() - 1) {26list.set(index, last);27map.put(last, index);28}29list.remove(list.size() - 1);30map.remove(val);31return true;32}33return false;34}3536public int getRandom() {37int r = rand.nextInt(list.size());38return list.get(r);39}40}