why not as simple as this?


  • 0
    G
    public class RandomizedSet {
        
        HashMap<Integer,Integer> map = new HashMap<>();
        ArrayList<Integer> as = new ArrayList<>();
    
        /** 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(map.containsKey(val)){
                return false;
            }
            map.put(val,as.size());
            as.add(val);
            return true;
        }
        
        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            if(!map.containsKey(val)){
                return false;
            }
            
            map.remove(val);
            as.remove(Integer.valueOf(val));
            return true;
        }
        
        /** Get a random element from the set. */
        public int getRandom() {
            Random r = new Random();
            return as.get(r.nextInt(as.size()));
        }
    }

Log in to reply
 

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