0
点赞
收藏
分享

微信扫一扫

leetcode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复 map

爱读书的歌者 2023-02-22 阅读 112


用一个map记录每一个元素出现的次数就可以
然后弄一个int记录总时间

这样 插入和删除的时候就将对应数字的mp值改掉就可以
但是获取随机元素就不是O(1)了 但是小于O(n)

class RandomizedCollection {
public:
map<int ,int >mp;
int cnt;
/** Initialize your data structure here. */
RandomizedCollection() {
srand(time(0));
cnt = 0;
}

/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
mp[val]++;
cnt++;
return true;
}

/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
--mp[val];
if(mp[val]>=0){
cnt--;
return true;
}else{
mp[val] = 0;
return false;
}
}

/** Get a random element from the collection. */
int getRandom() {
int ran = rand()% cnt+1;
map<int ,int >::iterator it = mp.begin();
for(; it!= mp.end();it++){
ran -= it->second;
if(ran<=0){
return it->first;
}
}
return it->first;
}
};

leetcode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复 map_map


举报

相关推荐

0 条评论