Bug report and my java solution


  • -1
    W

    The oj platform need to import random package and it need to change delete function to remove

    Set<Integer> set;
        /** Initialize your data structure here. */
        public RandomizedSet() {
            set = new HashSet<>();
        }
        
        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public boolean insert(int val) {
            if (set.contains(val)) {
                return false;
            }
            set.add(val);
            return true;
        }
        
        /** Deletes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            if (!set.contains(val)) {
                return false;
            }
            set.remove((Integer)val);
            return true;
        }
        
        /** Get a random element from the set. */
        public int getRandom() {
            
            int index = (int)Math.random()*set.size();
            int d = 0;
            for (int val : set) {
                if (d == index) {
                    return val;
                }
                d++;
            }
            return 0;
        }

  • 0
    W

    time for getRandom is not O(1)


Log in to reply
 

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