380. Insert Delete GetRandom O(1)
アプローチ
ArrayList, HashSet
class RandomizedSet {
public ArrayList<Integer> arrayList;
public Set<Integer> set;
public Random rm;
public RandomizedSet() {
arrayList = new ArrayList<>();
set = new HashSet<>();
rm = new Random();
}
public boolean insert(int val) {
if(set.contains(val)){
return false;
}
arrayList.add(val);
set.add(val);
return true;
}
public boolean remove(int val) {
if(!set.contains(val)){
return false;
}
set.remove(val);
arrayList.remove(new Integer(val));
return true;
}
public int getRandom() {
int idx = rm.nextInt(set.size());
return arrayList.get(idx);
}
}