My simple Java Solution with HashSet and ArrayList


  • 0
    A

    """
    class RandomizedSet {

    /** Initialize your data structure here. */
    HashSet<Integer> set;
    ArrayList<Integer> list;
    java.util.Random rand = new java.util.Random();
    public RandomizedSet() {
        set=new HashSet<Integer>();
        list=new ArrayList<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(set.contains(val))
            return false;
        set.add(val);
        list.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(!set.contains(val))
            return false;
        set.remove(val);
        list.remove(Integer.valueOf(val));
        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        return list.get(rand.nextInt(list.size()));
    }
    

    }
    """


Log in to reply
 

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