题目描述
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 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();
题意:设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
- insert(val):当元素 val 不存在时,向集合中插入该项。
- remove(val):元素 val 存在时,从集合中移除该项。
- getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。
算法1
(数组+哈希表)
题解:我们可以使用一个数组来存储已经插入的数字,同时使用一个哈希表来存储插入的数字和对应在数组中的下标,同时我们使用一个数组存储数组中已经有多少个数字了。
- insert:我们首先在哈希表中查看当前数字是否已经插入了$O(1)$,如果出现过返回false,如果没有出现过,那么将该数字插入数组末尾$O(1)$,同时更新哈希表$O(1)$。
- Remove:同样的我们首先在哈希表中查看当前数字是否已经插入过$O(1)$,如果没有出现过返回false,如果出现过,那么我们将数组的最后一个元素移到将要删除的元素位置上,同时更新哈希表中对应的下标,然后从哈希表中删除待删除元素的映射关系。
- Get random:生成一个$0-cnt$的随机数即可。
class RandomizedSet {
public:
/** Initialize your data structure here. */
vector<int> arr;
unordered_map<int,int> hash;
int cnt = 0;
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if(hash.find(val) == hash.end())
{
hash[val] = cnt ++;
arr.push_back(val);
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
auto it = hash.find(val);
if(it != hash.end())
{
int idx = it->second;
arr[idx] = arr.back();
hash[arr[idx]] = idx;
arr.pop_back();
cnt --;
hash.erase(it);
return true;
}
return false;
}
/** Get a random element from the set. */
int getRandom() {
return arr[rand() % cnt];
}
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/