Set and ArrayList 138ms very simple Java Solution


  • 0

    Hi,

    Can anyone please review my code. Its accepted by OJ and I just got it right in one attempt. So curious to know what more I can improve in terms of time/space complexity?

    public class RandomizedSet {
        private Set<Integer> set;
        private List<Integer> list;
        private Random ran;
        
        /** Initialize your data structure here. */
        public RandomizedSet() {
            set = new HashSet<>();
            list = new ArrayList<>();
            ran = 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)){
                 list.add(val);
                 return true;
             } else {
                 return false;
             }
        }
        
        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            return set.remove(val);
        }
        
        /** Get a random element from the set. */
        public int getRandom() {
            int size = list.size();
            int random_index = ran.nextInt(size);
            
            while(!set.contains(list.get(random_index))){
                random_index = ran.nextInt(size);
            }
    
            return list.get(random_index);
        }
    }
    
    /**
     * Your RandomizedSet object will be instantiated and called as such:
     * RandomizedSet obj = new RandomizedSet();
     * boolean param_1 = obj.insert(val);
     * boolean param_2 = obj.remove(val);
     * int param_3 = obj.getRandom();
     */
    

Log in to reply
 

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