class RandomizedSet {
Map<Integer,Integer> keyIndexMap;
Map<Integer,Integer> indexKeyMap;
int size;
/** Initialize your data structure here. */
public RandomizedSet() {
keyIndexMap=new HashMap<>();
indexKeyMap=new HashMap<>();
size=0;
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(keyIndexMap.containsKey(val)){
return false;
}
//一个size对应一个元素
keyIndexMap.put(val,size);
indexKeyMap.put(size,val);
size++;
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!keyIndexMap.containsKey(val)){
return false;
}
int deleteIndex=keyIndexMap.get(val);
int lastKey=indexKeyMap.get(size-1);
//将最后一个位置上的元素填充被删除的位置
keyIndexMap.put(replaceKey,deleteIndex);
indexKeyMap.put(deleteIndex,lastKey);
keyIndexMap.remove(val);
indexKeyMap.remove(size-1);
size--;
return true;
}
/** Get a random element from the set. */
public int getRandom() {
if(this.size==0){
return -1;
}
//获取的随机数在[0,size)范围内
int random=(int)(Math.random()*(this.size));
return this.indexKeyMap.get(random);
}
}