题目描述:
Design a data structure that supports all following operations in average O(1) time.
Note: Duplicate elements are allowed.
1. insert(val): Inserts an item val to the collection.
2. remove(val): Removes an item val from the collection if present.
3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.
Example:
// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();
// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);
// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);
// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);
// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();
// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);
// getRandom should return 1 and 2 both equally likely.
collection.getRandom();
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) {
v.push_back(val);
if(hash.count(val)==0)
{
hash[val]={v.size()-1};
return true;
}
else
{
hash[val].insert(v.size()-1);
return false;
}
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if(hash.count(val)==0) return false;
int i=*hash[val].begin();
//先将hash[val]中的i删除
if(hash[val].size()==1) hash.erase(hash.find(val));
else hash[val].erase(hash[val].begin());
if(i!=v.size()-1)
{ //如果i等于v.size()-1,那么就不需要再做交换
int x=v.back();
//再插入i,将hash[x]中的v.size()-1删除
hash[x].insert(i);
hash[x].erase(hash[x].find(v.size()-1));
swap(v[i],v.back());
}
v.pop_back();
return true;
}
/** Get a random element from the collection. */
int getRandom() {
return v[rand()%v.size()];
}
private:
unordered_map<int,unordered_set<int>> hash; // 哈希表记录数值和对应的下标集合
vector<int> v;
};
本文介绍了一种数据结构的设计,该结构支持平均O(1)时间复杂度的插入、删除和随机选择操作,允许元素重复。通过使用哈希表和动态数组,确保了高效的操作执行。
1874

被折叠的 条评论
为什么被折叠?



