解题思路:创建hashmap,一个存K,数字,另一个存数字,K,每当插入元素时,将元素非别对应插入两个hashmap中目的是能够方变随机查找。
public class RandomPool { public static class Pool<K>{ private HashMap<K,Integer> keyIndexMap; private HashMap<Integer,K> indexKeyMap; private int size; public Pool(){ keyIndexMap = new HashMap<>(); indexKeyMap = new HashMap<>(); size = 0; } public void insert(K key){ if(!keyIndexMap.containsKey(key)){ keyIndexMap.put(key,size); indexKeyMap.put(size++,key); } } // A 0 0 A // B 1 1 B //C 2 2 C //D 3 3 D //先确定删除的索引,以及最后面的值,把最后面的值补充到删除的地方 //之后删除开始应该删除的 public void delete(K key){ if(keyIndexMap.containsKey(key)){ int deleteIndex = keyIndexMap.get(key); int lastIndex = --size; K lastKey = indexKeyMap.get(lastIndex); keyIndexMap.put(lastKey,deleteIndex); indexKeyMap.put(deleteIndex,lastKey); keyIndexMap.remove(key); indexKeyMap.remove(lastIndex); } } public K random(){ if(size==0){ return null; } int num = (int) (Math.random()*size); return indexKeyMap.get(num); } }}总结:多积累。
原文地址:https://www.cnblogs.com/liuwentao/p/9404305.html
时间: 2024-10-08 18:43:58