381 Insert Delete GetRandom O(1) - Duplicates allowed O(1) 時間插入、刪除和獲取隨機元素 - 允許重復
設計一個支持在平均 時間復雜度 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();
詳見:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
C++:
class RandomizedCollection { public: /** Initialize your data structure here. */ RandomizedCollection() {} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { m[val].insert(nums.size()); nums.push_back(val); return m[val].size() == 1; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { if (m[val].empty()) { return false; } int idx = *m[val].begin(); m[val].erase(idx); if (nums.size() - 1 != idx) { int t = nums.back(); nums[idx] = t; m[t].erase(nums.size() - 1); m[t].insert(idx); } nums.pop_back(); return true; } /** Get a random element from the collection. */ int getRandom() { return nums[rand() % nums.size()]; } private: vector<int> nums; unordered_map<int, unordered_set<int>> m; };
參考:http://www.cnblogs.com/grandyang/p/5756148.html
381 Insert Delete GetRandom O(1) - Duplicates allowed O(1) 時間插入、刪除和獲取隨機元素 - 允許重復