Test Case issue? cannot pass by random selection


  • 0
    C
    
    public class RandomizedSet {
    
        List<Integer> list = new ArrayList<Integer>();
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        
        /** Initialize your data structure here. */
        public RandomizedSet() {
            
        }
        
        /** 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);
            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 last = list.get(list.size()-1);
            int idx = map.get(val);
            if(list.size()-1 != idx){
                list.set(idx, last);
                map.put(last, idx);
            }
            map.remove(val);
            return true;
        }
        
        /** Get a random element from the set. */
        public int getRandom() {
             // can't pass by random select?
        //   java.util.Random random = new java.util.Random();
        //   int idx = random.nextInt(list.size());
          
          return list.get(0);
            
        }
    }
    

  • 0
    G

    +1

    Also, the Java skeleton was wrong. The test code seems to expect a "remove" method to exist, but the skeleton only has "delete". (Renaming the "delete" method to "remove" fixed it.) I think this is a very poorly tested question.


  • 0

    @codingwhite said in Test Case issue? cannot pass by random selection:

    public boolean remove(int val) {
    if(!map.containsKey(val)){
    return false;
    }
    int last = list.get(list.size()-1);
    int idx = map.get(val);
    if(list.size()-1 != idx){
    list.set(idx, last);
    map.put(last, idx);
    }
    map.remove(val);
    list.remove(list.size()-1);
    return true;
    }

    There is a bug in the code. Need to delete the last one from the list.


  • 0
    C

    @yubad2000 yes thanks


Log in to reply
 

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