public class RandomPool<T> {
/**
* 设计一种结构,在该结构中有如下三个功能
* insert(key): 将某个key加入到该结构,做到不重复加入
* delete(key):将原本在结构中的某个key移除
* getRadom():等概率随机返回结构中的任何一个key
*/
Map<Integer,T> dataMap;
Map<T,Integer> dataK;
int size;
public RandomPool() {
this.dataMap = new HashMap<>();
this.dataK = new HashMap<>();
}
public void insert(T key) {
Integer k = this.dataK.get(key);
if(k == null) {
this.size++;
this.dataK.put(key, this.size);
this.dataMap.put(this.size, key);
}
}
public void delete(T key) {
Integer k = this.dataK.get(key);
if(k != null) {
this.dataK.remove(key);
this.dataMap.remove(k);
if(!k.equals(this.size)) {
T last = this.dataMap.get(this.size);
this.dataK.put(last, k);
this.dataMap.put(k, last);
this.dataMap.remove(this.size);
this.size--;
}
}
}
public T getRandom() {
int key = (int) (Math.random()*size+1);
return this.dataMap.get(key);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RandomPool<String> randomPool = new RandomPool<>();
randomPool.insert("1");
randomPool.insert("2");
randomPool.insert("3");
randomPool.insert("4");
randomPool.delete("2");
for(int i = 0;i<9;i++) {
System.out.print(" ,"+randomPool.getRandom());
}
}
}