【题目】
设计一种结构满足如下3个功能
insert(key):将某个key加入到该结构,做到不重复添加
delete(key):将原本在结构中的某个key移除
getRandom():等概率随机返回结构中任意key
【要求】
3个方法的时间复杂度要求O(1)
public class RandomPool {
public static class Pool<K>{
private HashMap<K, Integer> keyIndexMap;
private HashMap<Integer, K> indexKeyMap;
private int size;
public Pool() {
this.keyIndexMap = new HashMap<>();
this.indexKeyMap = new HashMap<>();
this.size = 0;
}
public void insert(K key){
//控制不重复添加
if (keyIndexMap.containsKey(key)){
return;
}
keyIndexMap.put(key, size);
indexKeyMap.put(size++, key);
}
public void delete(K key){
if (!keyIndexMap.containsKey(key)){
return;
}
//要删除的
int deleteKIndex = keyIndexMap.get(key);
int lastIndex = --size;
//最后一个数据
K lastKey = indexKeyMap.get(lastIndex);
keyIndexMap.put(lastKey, deleteKIndex);
indexKeyMap.put(deleteKIndex, lastKey);
keyIndexMap.remove(key);
indexKeyMap.remove(lastIndex);
}
public K getRandom(){
if (size == 0){
return null;
}
int randomIndex = (int) (Math.random() * size);
return this.indexKeyMap.get(randomIndex);
}
}
public static void main(String[] args) {
Pool<String> pool = new Pool<>();
pool.insert("hi");
pool.insert("hi");
pool.insert("happy");
pool.insert("every");
pool.insert("day");
pool.delete("every");
String random = pool.getRandom();
System.out.println(random);
}
}