Java accepted solution only use one set, no list and simple


  • 0
    P
    class RandomizedSet {
        Set<Integer> set;
        Random random;
    
        /** Initialize your data structure here. */
        public RandomizedSet() {
            set = new HashSet<Integer>();
            random = 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) {
            return set.add(val);
        }
        
        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
                return set.remove(val);
        }
        
        /** Get a random element from the set. */
        /* May not be O(1) operation */
        public int getRandom() {
            Iterator<Integer> iterator = set.iterator();
            int count = random.nextInt(set.size());
            int res = -1;
            while (count-- >= 0 && iterator.hasNext()) {
                res = iterator.next();
            }
            return res;
        }
    }
    

Log in to reply
 

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