BiruLyu
5/31/2017 - 6:44 PM

381. Insert Delete GetRandom O(1) - Duplicates allowed.java

public class RandomizedCollection {

    /** Initialize your data structure here. */
    private HashMap<Integer, LinkedHashSet<Integer>> locations;
    private ArrayList<Integer> nums;
    private Random rand = new Random();
    public RandomizedCollection() {
        locations = new HashMap<Integer, LinkedHashSet<Integer>>();
        nums = new ArrayList<Integer>();
    }
    
    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    public boolean insert(int val) {
        boolean isContains = locations.containsKey(val);
        if(!isContains) {
            locations.put(val, new LinkedHashSet<Integer>());
        }
        locations.get(val).add(nums.size());
        nums.add(val);
        return !isContains;
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    public boolean remove(int val) {
        if(!locations.containsKey(val)) {
            return false;
        }
        int location = locations.get(val).iterator().next();
        locations.get(val).remove(location);
        int last = nums.size() - 1;
        if(location != last) {
            int lastone = nums.get(last);
            locations.get(lastone).remove(last);
            locations.get(lastone).add(location);
            nums.set(location, lastone);
        }
        nums.remove(last);
        if (locations.get(val).isEmpty()) {
            locations.remove(val);
        } 
        return true;
    
    }
    
    /** Get a random element from the collection. */
    public int getRandom() {
        return nums.get(rand.nextInt(nums.size()));
    }
}

/**
 * Your RandomizedCollection object will be instantiated and called as such:
 * RandomizedCollection obj = new RandomizedCollection();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */