here hashmap is used only for search whole work is done by array
@2amCoder9 ай бұрын
HashMap map; ArrayList li; public RandomizedSet() { map = new HashMap(); li = new ArrayList(); } public boolean insert(int val) { if (map.containsKey(val)) return false; map.put(val, li.size()); li.add(val); return true; } public boolean remove(int val) { if (!map.containsKey(val)) return false; int idxToRemove = map.get(val); int lastVal = li.get(li.size() - 1); li.set(idxToRemove, lastVal); map.put(lastVal, idxToRemove); map.remove(val); li.remove(li.size() - 1); return true; } public int getRandom() { int randomIdx = (int) (Math.random() * li.size()); return li.get(randomIdx); }we dont need 3rd var