Concise JAVA answer


  • -1
    L
    public class RandomizedSet {
    
        List<Integer> nums;
        Set<Integer> set;
        Random rd;
        
        /** Initialize your data structure here. */
        public RandomizedSet() {
            nums = new LinkedList<>();
            set = new HashSet<>();
            rd = 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.add(val)){
                nums.add(val);
                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(set.remove(val)){
                nums.remove(new Integer(val));
                return true;
            }
            return false;
        }
        
        /** Get a random element from the set. */
        public int getRandom() {
            return nums.get(rd.nextInt(set.size()));
        }
    }
    

  • 0
    C

    ArrayList.remove() takes O(n), you solution is incorrect


Log in to reply
 

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