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()));
}
}
380. Insert Delete GetRandom O(1)
最新推荐文章于 2023-03-17 22:25:05 发布