LeetCode 380. Insert Delete GetRandom $O(1)$
Implement the RandomizedSet class:
RandomizedSet()
Initializes theRandomizedSet
object.bool insert(int val)
Inserts an itemval
into the set if not present. Returnstrue
if the item was not present,false
otherwise.bool remove(int val)
Removes an item val from the set if present. Returnstrue
if the item was present,false
otherwise.int getRandom()
Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in average $O(1)$ time complexity.
Example 1:
Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]
Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
method
集合没办法实现等可能地获取一个元素,所以需要有下标的数组来完成随机取数,但数组没办法实现$O(1)$地删除一个数,除非能知道这个数的下标,这样可以把这个数换到末尾然后删除,所以用一个哈希表存储元素和下标的对应关系
class RandomizedSet {
public:
unordered_map<int, int> hash; // elem -> index
vector<int> arr; // 数组实现随机取数
RandomizedSet() {}
bool insert(int val) {
if (hash.find(val) != hash.end()) return false;
arr.push_back(val); // 数组增加元素
hash[val] = arr.size() - 1; // 哈希表增加<元素-下标>对
return true;
}
bool remove(int val) {
if (hash.find(val) == hash.end()) return false;
hash[arr.back()] = hash[val]; // 在哈希表中修改最后一个元素的下标
arr[hash[val]] = arr.back(); // 数组中要删除的元素的位置换成最后一个元素
arr.pop_back(); // 删除最后一个元素
hash.erase(val); // 删除<元素-下标>对
return true;
}
int getRandom() {
int idx = rand() % arr.size(); // 随机获取下标
return arr[idx];
}
};