LC.P380[O(1)时间插入、删除和获取随机元素] 方法一:Map+List12345678910111213141516171819202122232425262728293031323334353637383940414243class RandomizedSet { Map<Integer, Integer> map; List<Integer> list; Random random; public RandomizedSet() { map = new HashMap<>(); list = new ArrayList<>(); random = new Random(); } public boolean insert(int val) { if (map.containsKey(val)) return false; map.put(val, list.size()); list.add(val); return true; } public boolean remove(int val) { if (!map.containsKey(val)) return false; int size = list.size(); Integer lastVal = list.get(size - 1); int index = map.get(val); list.set(index, lastVal); map.put(lastVal, index); list.remove(size - 1); map.remove(val); return true; } public int getRandom() { return list.get(random.nextInt(list.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(); */ 时间复杂度:$O(1)$ 空间复杂度:$O(n)$