A simple Java solution(may not meet the requirement)


  • 0

    I used a hash set to store input as Integer to check whether the input exists and a list to store input as Integer so that we can know how many inputs we have in every moment. When call getRandom(), I will generate a random number between 0 to the total number of element in the list as an index. So all the probability of getting number are same.
    '''

    public class RandomizedSet {
    List<Integer> list;
    Set<Integer> hash;
    /** Initialize your data structure here. */
    public RandomizedSet() {
        list = new ArrayList<>();
        hash = new HashSet<>();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if (hash.contains(val)){
            return false;
        }
        Integer i = val;
        list.add(i);
        return hash.add(i);
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if (hash.contains(val)){
            Integer i = val;
            list.remove(i);
            hash.remove(i);
            return true;
        }
        return false;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        int i = (int) (Math.random() * list.size());
        return list.get(i);
    }
    

    }

    '''


Log in to reply
 

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