BiruLyu
5/31/2017 - 5:41 PM

380. Insert Delete GetRandom O(1).java

public class RandomizedSet {

    /** Initialize your data structure here. */
    private HashMap<Integer, Integer> sequence;
    private ArrayList<Integer> nums;
    private Random rand = new Random();
    public RandomizedSet() {
        sequence = new HashMap<Integer, Integer>();
        nums = 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(sequence.containsKey(val)) {
            return false;
        }
        sequence.put(val, nums.size());
        nums.add(val);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if(!sequence.containsKey(val)) {
            return false;
        }
        int seq = sequence.get(val);
        int last = nums.size() - 1;
        if(seq != last) {
            int lastone = nums.get(last);
            nums.set(seq, lastone);
            sequence.put(lastone, seq);
        }
        sequence.remove(val);
        nums.remove(last);
        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        return nums.get(rand.nextInt(nums.size()));
    }
}

/**
 * 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();
 */