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()];
    }
};
相关推荐
水饺编程6 分钟前
第5章,[标签 Win32] :获取设备环境的信息
c语言·c++·windows·visual studio
lhbian7 分钟前
C++、C与易语言:编程语言对比解析
c语言·开发语言·c++
hehelm13 分钟前
二叉搜索树
c++
云泽80835 分钟前
笔试算法 - 双指针篇(一):移动零、复写零、快乐数与盛水容器
c++·算法
小堃学编程36 分钟前
【项目实战】基于protobuf的发布订阅式消息队列(4)—— 服务端
c语言·c++·vscode·消息队列·gtest·protobuf·muduo
小白学大数据1 小时前
解决 Python 爬虫被限制:延迟抓取指令深度解析
开发语言·c++·爬虫·python
会编程的土豆1 小时前
【复习】二分查找
数据结构·c++·算法
yuanpan2 小时前
Python 调用 DLL 动态库入门:Windows 下调用 C++ 与 C# 动态库完整示例
c++·windows·python
handler013 小时前
Linux: 基本指令知识点(3)
linux·服务器·c语言·开发语言·c++·笔记
wuminyu3 小时前
专家视角看Java线程生命周期与上下文切换的本质
java·linux·c语言·jvm·c++