C++ | Leetcode C++题解之第381题O(1)时间插入、删除和获取随机元素-允许重复

题目:

题解:

cpp 复制代码
class RandomizedCollection {
public:
    unordered_map<int, unordered_set<int>> idx;
    vector<int> nums;

    /** 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) {
        nums.push_back(val);
        idx[val].insert(nums.size() - 1);
        return idx[val].size() == 1;
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        if (idx.find(val) == idx.end()) {
            return false;
        }
        int i = *(idx[val].begin());
        nums[i] = nums.back();
        idx[val].erase(i);
        idx[nums[i]].erase(nums.size() - 1);
        if (i < nums.size() - 1) {
            idx[nums[i]].insert(i);
        }
        if (idx[val].size() == 0) {
            idx.erase(val);
        }
        nums.pop_back();
        return true;
    }
    
    /** Get a random element from the collection. */
    int getRandom() {
        return nums[rand() % nums.size()];
    }
};
相关推荐
wuqingshun31415917 分钟前
蓝桥杯 16. 密文搜索
c++·算法·职场和发展·蓝桥杯·深度优先
LuckyRich135 分钟前
【仿Mudou库one thread per loop式并发服务器实现】服务器边缘测试+性能测试
服务器·c++
小邓儿◑.◑7 小时前
C++武功秘籍 | 入门知识点
开发语言·c++
杨筱毅10 小时前
【优秀三方库研读】【C++基础知识】odygrd/quill -- 折叠表达式
c++·三方库研读
hjjdebug11 小时前
c++中的enum变量 和 constexpr说明符
c++·enum·constexpr
CoderCodingNo11 小时前
【GESP】C++二级真题 luogu-B4259 [GESP202503 二级] 等差矩阵
java·c++·矩阵
明月看潮生11 小时前
青少年编程与数学 02-018 C++数据结构与算法 11课题、分治
c++·算法·青少年编程·编程与数学
Echo``12 小时前
2:QT联合HALCON编程—图像显示放大缩小
开发语言·c++·图像处理·qt·算法
想睡hhh13 小时前
c++STL——stack、queue、priority_queue的模拟实现
开发语言·c++·stl
cloues break.13 小时前
C++初阶----模板初阶
java·开发语言·c++