share my java solution(130ms)


  • 0
    C
    public class RandomizedSet {
        List<Integer> list;
        Map<Integer,Integer> map;
        Random rand = new Random();
        int size=0;
        /** Initialize your data structure here. */
        public RandomizedSet() {
            list=new ArrayList<>();
            map=new HashMap<>();
        }
        
        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public boolean insert(int val) {
            if(map.containsKey(val)) return false;
            list.add(val);
            map.put(val,list.size()-1);
            size++;
            return true;
        }
        
        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            if(!map.containsKey(val)) return false;
            int index=map.get(val);
            if(index==size-1){
                list.remove(size-1);
                map.remove(val);
            }else{
                list.set(index,list.get(size-1));
                list.remove(size-1);
                map.remove(val);
                map.put(list.get(index),index);
            }
            size--;
            return true;
        }
        
        /** Get a random element from the set. */
        public int getRandom() {
            int index=rand.nextInt(size);
            return list.get(index);
        }
    }
    
    

Log in to reply
 

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