設計一個支持在平均 時間復雜度 O(1) 下, 執行以下操作的數據結構。
注意: 允許出現重復元素。
insert(val):向集合中插入元素 val。
remove(val):當 val 存在時,從集合中移除一個 val。
getRandom:從現有集合中隨機獲取一個元素。每個元素被返回的概率應該與其在集合中的數量呈線性相關。
示例:
// 初始化一個空的集合。
RandomizedCollection collection = new RandomizedCollection();
// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);
// 向集合中插入另一個 1 。返回 false 表示集合包含 1 。集合現在包含 [1,1] 。
collection.insert(1);
// 向集合中插入 2 ,返回 true 。集合現在包含 [1,1,2] 。
collection.insert(2);
// getRandom 應當有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();
// 從集合中刪除 1 ,返回 true 。集合現在包含 [1,2] 。
collection.remove(1);
// getRandom 應有相同概率返回 1 和 2 。
collection.getRandom();
代碼
class RandomizedCollection {Map<Integer,Integer> map=new HashMap<>();LinkedList<Integer> list=new LinkedList<>();//插入的數字鏈表Map<Integer,Boolean> booleanMap=new HashMap<>();//記錄當前索引中的數字是否可選Map<Integer,LinkedList<Integer>> queueMap=new HashMap<>();//數字對應的在數字鏈表的索引/** Initialize your data structure here. */public RandomizedCollection() {}/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */public boolean insert(int val) {list.addLast(val);booleanMap.put(list.size()-1,true);if(!queueMap.containsKey(val)){queueMap.put(val,new LinkedList<>());}queueMap.get(val).add(list.size()-1);//插入當前數字的數字鏈表的索引if(map.containsKey(val)&&map.get(val)>0){map.put(val,map.get(val)+1);return false;}else{map.put(val, 1);return true;}}/** Removes a value from the collection. Returns true if the collection contained the specified element. */public boolean remove(int val) {if(!queueMap.containsKey(val)||queueMap.get(val).isEmpty()) return false;int cur=queueMap.get(val).removeFirst();//移出索引鏈表booleanMap.put(cur,false);//標記為不可選if(map.containsKey(val)&&map.get(val)>0){map.put(val,map.get(val)-1);return true;}else return false;}/** Get a random element from the collection. */public int getRandom() {Random random=new Random();int c=random.nextInt(list.size());while (!booleanMap.get(c))//跳過不可選的位置c=random.nextInt(list.size());return list.get(c);}}
/*** Your RandomizedCollection object will be instantiated and called as such:* RandomizedCollection obj = new RandomizedCollection();* boolean param_1 = obj.insert(val);* boolean param_2 = obj.remove(val);* int param_3 = obj.getRandom();*/