publicclassRandomizedCollection {ArrayList<Integer> list;HashMap<Integer,LinkedHashSet<Integer>> map;Random rand; /** Initialize your data structure here. */publicRandomizedCollection() { list =newArrayList<Integer>(); map =newHashMap<Integer,LinkedHashSet<Integer>>(); rand =newRandom(); } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
publicbooleaninsert(int val) {boolean isContain =map.containsKey(val);if (isContain) {list.add(val);map.get(val).add(list.size() -1);returnfalse; } else {list.add(val);map.put(val,newLinkedHashSet<Integer>());map.get(val).add(list.size() -1);returntrue; } } /** Removes a value from the collection. Returns true if the collection contained the specified element. */publicbooleanremove(int val) {boolean isContain =map.containsKey(val);if (!isContain) returnfalse;int curPos =map.get(val).iterator().next();map.get(val).remove(curPos);if (curPos <list.size() -1) {int lastVal =list.get(list.size() -1);list.set(curPos, lastVal);map.get(lastVal).remove(list.size() -1);map.get(lastVal).add(curPos); }list.remove(list.size() -1);if (map.get(val).isEmpty()) {map.remove(val); }returntrue; } /** Get a random element from the collection. */publicintgetRandom() {returnlist.get(rand.nextInt(list.size())); }}/** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection obj = new RandomizedCollection(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */