Use LinkedHashSet, not very efficient but very easy to understand.


  • -2
    E

    Use LinkedHashSet to maintain the order of the elements.

    public class RandomizedSet {

    LinkedHashSet<Integer> set;
    Random random;
    
    /** Initialize your data structure here. */
    public RandomizedSet() {
        set = new LinkedHashSet<>();
        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) {
        if (set.contains(val))
        {
        	return false;
        }
        else
        {
        	set.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)){
        	set.remove(val);
        	return true;
        }
        else 
        	return false;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        int i = random.nextInt(set.size());
        for (int value: set){
        	if (i == 0)
        		return value;
        	else
        		i--;
        }
        
        return -1;
    }
    

    }


Log in to reply
 

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