380. Insert Delete GetRandom O(1)

public class RandomizedSet {
    ArrayList nums;
    HashMap map;
    java.util.Random rand=new java.util.Random();
    /** Initialize your data structure here. */
    public RandomizedSet() {
        nums=new ArrayList<>();
        map=new HashMap<>();
    }
    
    /** 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;
        map.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(!map.containsKey(val)) return false;
        int num=map.get(val);
        if(num

你可能感兴趣的:(380. Insert Delete GetRandom O(1))