Share my two-hashtable Java approach

  • 0
    //import java.util.NoSuchElementException;
    //import javax.swing.undo.CannotRedoException;
    public class RandomizedSet {
        private Map<Integer, Integer> map1 = new HashMap<>(), map2 = new HashMap<>();
        int counter = 0;
        /** Initialize your data structure here. */
        public RandomizedSet() {
        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public boolean insert(int val) {
            //if(map2.containsKey(val)) throw new CannotRedoException();
            if(map2.containsKey(val)) return false;
            map1.put(counter, val);
            map2.put(val, counter);
            return true;
        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            //if (!map2.containsKey(val)) throw new NoSuchElementException();
            if (!map2.containsKey(val)) return false;
            int ctKey = map2.get(val);
            int lastValue = map1.get(counter);
            map1.put(ctKey, lastValue);
            map2.put(lastValue, ctKey);
            return true;
        /** Get a random element from the set. */
        public int getRandom() {
            //if(map2.isEmpty()) throw new NoSuchElementException();
            if(map1.isEmpty()) return 0;
            int randomKey = (int)Math.floor(Math.random()*counter) + 1;
            return map1.get(randomKey);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.