380. Insert Delete GetRandom O(1)

来源:互联网 发布:淘宝的孕妇装 编辑:程序博客网 时间:2024/06/05 16:30
public class RandomizedSet {    private HashMap<Integer,Integer> m;    private ArrayList<Integer> a;    private Random r;    /** Initialize your data structure here. */    public RandomizedSet() {        m=new HashMap<>();        a=new ArrayList<>();        r=new Random();    }    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */    public boolean insert(int val) {        if(m.containsKey(val))            return false;        a.add(val);        m.put(val,a.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(m.containsKey(val)){            int index=m.get(val);            if(index<a.size()-1)            {                int lastval=a.get(a.size()-1);                a.set(index, lastval);                m.put(lastval,index);            }            a.remove(a.size()-1);            m.remove(val);            return true;        }        else            return false;    }    /** Get a random element from the set. */    public int getRandom() {        return a.get(r.nextInt(a.size()));    }}
0 0