Design a data structure that supports all following operations in average O(1) time.
insert(val): Inserts an item val to the set if not already present.remove(val): Removes an item val from the set if present.getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
Example:
// Init an empty set. RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomSet.insert(1); // Returns false as 2 does not exist in the set. randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomSet.insert(2); // getRandom should return either 1 or 2 randomly. randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. randomSet.remove(1); // 2 was already in the set, so return false. randomSet.insert(2); // Since 1 is the only number in the set, getRandom always return 1. randomSet.getRandom();
這道題讓我們在常數時間范圍內實現插入刪除和獲得隨機數操作,如果這道題沒有常數時間的限制,那么將會是一道非常簡單的題,直接用一個 HashSet 就可以搞定所有的操作。但是由於時間的限制,無法在常數時間內實現獲取隨機數,所以只能另辟蹊徑。此題的正確解法是利用到了一個一維數組和一個 HashMap,其中數組用來保存數字,HashMap 用來建立每個數字和其在數組中的位置之間的映射,對於插入操作,先看這個數字是否已經在 HashMap 中存在,如果存在的話直接返回 false,不存在的話,將其插入到數組的末尾,然后建立數字和其位置的映射。刪除操作是比較 tricky 的,還是要先判斷其是否在 HashMap 里,如果沒有,直接返回 false。由於 HashMap 的刪除是常數時間的,而數組並不是,為了使數組刪除也能常數級,實際上將要刪除的數字和數組的最后一個數字調換個位置,然后修改對應的 HashMap 中的值,這樣只需要刪除數組的最后一個元素即可,保證了常數時間內的刪除。而返回隨機數對於數組來說就很簡單了,只要隨機生成一個位置,返回該位置上的數字即可,參見代碼如下:
class RandomizedSet { public: RandomizedSet() {} bool insert(int val) { if (m.count(val)) return false; nums.push_back(val); m[val] = nums.size() - 1; return true; } bool remove(int val) { if (!m.count(val)) return false; int last = nums.back(); m[last] = m[val]; nums[m[val]] = last; nums.pop_back(); m.erase(val); return true; } int getRandom() { return nums[rand() % nums.size()]; } private: vector<int> nums; unordered_map<int, int> m; };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/380
類似題目:
Insert Delete GetRandom O(1) - Duplicates allowed
參考資料:
https://leetcode.com/problems/insert-delete-getrandom-o1/
