Why doesn't this work?


  • 0
    T

    I'm passing 16/18 test cases. It says I'm getting the wrong answer for one of the really long test cases. I have gone through my code countless times and can't figure out why it would return the wrong answer. I'm wondering if there is some kind of error with the oj checking against random values.

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

    }


Log in to reply
 

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