https://leetcode-cn.com/problems/insert-delete-getrandom-o1/
class RandomizedSet {
HashMap<Integer,Integer> map;
ArrayList<Integer> list;
Random random;
public RandomizedSet() {
map=new HashMap<>();
list=new ArrayList<>();
random=new Random();
}
public boolean insert(int val) {
if(map.containsKey(val)){
return false;
}
else{
int index=list.size();
map.put(val,index);
list.add(val);
return true;
}
}
public boolean remove(int val) {
if(!map.containsKey(val)){
return false;
}
int index=map.get(val);
int last=list.get(list.size()-1);
if(last!=val){
list.remove(list.size()-1);
list.set(index,last);
map.remove(val);
map.put(last,index);
return true;
}
else{
list.remove(list.size()-1);
map.remove(val);
return true;
}
}
public int getRandom() {
int index=random.nextInt(list.size());
return list.get(index);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/