Java Solution with just One HashMap


  • 0
    M

    ///
    class RandomizedSet {

    /** Initialize your data structure here. */
    HashMap<Integer, Integer> mapping;
    public RandomizedSet() {
        
    mapping = new HashMap<Integer, Integer>();
        
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        
        if(mapping.containsKey(val)){
            return false;
        }
        
        mapping.put(val, val);
        
        return true;
        
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        
        if(!mapping.containsKey(val)){
            return false;
        }
        
        mapping.remove(val);
        
        return true;
       
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        
        int size = mapping.size();
        
        Set<Integer> keys = mapping.keySet();
        Object[] arr = keys.toArray();
        
        Random rand = new Random();
        int key = rand.nextInt(size);
        
        return Integer.valueOf(arr[key].toString());
    }
    

    } ///


Log in to reply
 

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