classRandomizedSet{ HashMap<Integer,Integer> map; List<Integer> list; Random rd = new Random(); /** Initialize your data structure here. */ publicRandomizedSet(){ map = new HashMap<>(); list = new ArrayList<>(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ publicbooleaninsert(int val){ Integer index = map.get(val); if(index != null && list.get(index)!=null ) returnfalse; else{ list.add(val); map.put(val,list.size()-1); returntrue; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ publicbooleanremove(int val){ Integer index = map.get(val); if(index!=null&& list.get(index)!=null){ list.set(index,null); returntrue; }else returnfalse; } /** Get a random element from the set. */ publicintgetRandom(){ Integer index = rd.nextInt(list.size()); while(list.get(index)==null){ index = rd.nextInt(list.size()); } return list.get(index); } }
/** * 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(); */