publicclassRandomizedSet{ private HashMap<Integer, Integer> map; private List<Integer> elements; privatestatic Random random = new Random();
/** Initialize your data structure here. */ publicRandomizedSet(){ map = new HashMap<>(); elements = new ArrayList<>(); } /** 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)) { map.put(val, elements.size()); elements.add(val); returntrue; } returnfalse; } /** Removes a value from the set. Returns true if the set contained the specified element. */ publicbooleanremove(int val){ if (map.containsKey(val)) { int loc = map.get(val); map.remove(val, loc); if (loc != elements.size() - 1) { int end = elements.get(elements.size() - 1); map.put(end, loc); elements.set(loc, end); } elements.remove(elements.size() - 1); returntrue; } returnfalse; } /** Get a random element from the set. */ publicintgetRandom(){ return elements.get(random.nextInt(elements.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(); */