Is this a valid solution? It passes all tests...


  • 0
    W
    public class RandomizedSet {
    
        /** Initialize your data structure here. */
        private HashMap<Integer, Integer> map;
        private Random gen;
        public RandomizedSet() {
            this.map = new HashMap<>();
            this.gen = new Random();
        }
        
        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public boolean insert(int val) {
            if (!map.containsKey(val)) {
                map.put(val, 0);
                return true;
            }
            return false;
        }
        
        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            if (map.containsKey(val)) {
                map.remove(val);
                return true;
            }
            return false;
        }
        
        /** Get a random element from the set. */
        public int getRandom() {
            Object[] values = map.keySet().toArray();
            int index = gen.nextInt(values.length);
            return (int) values[index];
        }
    }
    

  • 0
    D

    @wolfadam14 I am guessing this isn't valid because map.keySet().toArray(); is O(n) and not O(1).


Log in to reply
 

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