题目:
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();
思路:
题目要求insert和remove都为近似O(1)的时间复杂度,这在我们所学的数据结构中只有哈希表可以做到这一点。然而哈希表并不支持getRandom。为了支持random,我们额外给哈希表中的每个元素“编个号”,建立索引和哈希表之间的对应关系,这样我们既可以用O(1)的时间实现对哈希表的操作,又在有索引的情况下,在O(1)的时间内随机获得哈希表中的元素。我们定义的两个数据结构如下:
1)哈希表unordered_map<int, int> hash:从哈希元素到索引的映射。这样当对哈希表进行增删操作的时候,我们可以在O(1)的时间内对索引表进行相应操作。
2)索引表vector<int> indices:从索引到哈希元素的映射。这样当我们获得随机元素的索引后,立即就可以获得对应的哈希元素,从而保证getRandom的时间复杂度为O(1)。
在实现中唯一需要注意的是技巧是:在remove的时候,如果发现要删除的元素不在索引表的末尾,我们就先将索引表中要删除的元素和末尾元素进行交换,再在索引表中删除,这样可以保证对索引表的操作也在O(1)的时间内完成。
代码:
class RandomizedSet {
public:
/** Initialize your data structure here. */
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.count(val) == 0) {
hash[val] = indices.size();
indices.push_back(val);
return true;
}
else {
return false;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if(hash.count(val) == 0) {
return false;
}
else {
int index = hash[val];
if(index + 1 == indices.size()) {
hash.erase(val);
indices.pop_back();
}
else {
int last_value = indices.back();
hash[last_value] = index; // reconstruct the relationship
indices[index] = last_value;
hash.erase(val);
indices.pop_back();
}
return true;
}
}
/** Get a random element from the set. */
int getRandom() {
if(indices.size() == 0) {
return -1;
}
return indices[rand() % indices.size()];
}
private:
unordered_map<int, int> hash; // map from value to index
vector<int> indices;
};
/**
* 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();
*/