486 字
2 分钟
380. O(1) 时间插入、删除和获取随机元素

380. O(1) 时间插入、删除和获取随机元素#

实现RandomizedSet 类:

RandomizedSet() 初始化 RandomizedSet 对象 bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。 bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。 int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。 你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1) 。

可以借助unordered_mapvector 来实现。

示例#

输入
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
输出
[null, true, false, true, 2, true, false, 2]
解释
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。

代码#

class RandomizedSet {
public:
RandomizedSet() {
srand((unsigned)time(NULL));
}
bool insert(int val) {
// val exists
if(_indices.count(val)){
return false;
}
// val not exist
// get last index and add val
int index = _nums.size();
_nums.emplace_back(val);
// record index
_indices[val] = index;
return true;
}
bool remove(int val) {
// val not exist
if(!_indices.count(val)){
return false;
}
// get val index
int index = _indices[val];
int last = _nums.back();
// move last val to replace current val
_nums[index] = last;
_indices[last] = index;
// remove last val
_nums.pop_back();
_indices.erase(val);
return true;
}
int getRandom() {
int random_index = rand()%_nums.size();
return _nums[random_index];
}
private:
vector<int> _nums;
unordered_map<int, 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();
*/
380. O(1) 时间插入、删除和获取随机元素
https://chrisnake11.github.io/blog/posts/coding/leecode/380-o1-时间插入删除和获取随机元素/
作者
Zheyv
发布于
2025-08-03
许可协议
CC BY-NC-SA 4.0