140 ms Java solution


  • 0
    J

    '''
    public class RandomizedSet {

    HashMap<Integer,Integer> indexMap;
    ArrayList<Integer> setList;
    int last;
    /** Initialize your data structure here. */
    public RandomizedSet() {
        
        setList = new ArrayList<Integer>();
        indexMap = new HashMap<Integer,Integer>();
        last=0;
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        
        if(!indexMap.containsKey(val))
        {
            setList.add(val);
            last=setList.size()-1;
            indexMap.put(val,last);
            return true;
        }
        
        return false;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        
        if(indexMap.containsKey(val))
        {
            int index=indexMap.get(val);
            if(index==last)
            {
                indexMap.remove(val);
                setList.remove(last);
                last--;
                 return true;
            }
            
            int newVal = setList.get(last);
            setList.remove(last);
            last--;
            setList.set(index,newVal);
            indexMap.remove(val);
            indexMap.put(newVal,index);
            return true;
            
        }
        
        return false;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        
        int randIndex = (int)(Math.random()*(last+1));
        
        return setList.get(randIndex);
        
    }
    

    }

    '''


Log in to reply
 

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