Map<Integer, Integer> map; List<Integer> list; Random random;
/** * Initialize your data structure here. */ publicRandomizedSet() { map = newHashMap<>(); list = newArrayList<>(); random = newRandom(); }
/** * Inserts a value to the set. Returns true if the set did not already contain the specified element. */ publicbooleaninsert(int val) { if (map.containsKey(val)) returnfalse; map.put(val, list.size()); list.add(val); returntrue; }
/** * Removes a value from the set. Returns true if the set contained the specified element. */ publicbooleanremove(int val) { if (!map.containsKey(val)) returnfalse; intsize= list.size(); intindex= map.get(val); intlastVal= list.get(size - 1); map.put(lastVal, index); map.remove(val); list.set(index, lastVal); list.remove(size - 1); returntrue; }
/** * Get a random element from the set. */ publicintgetRandom() { 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(); */