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()];
    }
};
相关推荐
liulilittle6 分钟前
SQLite3 C++ usage demo
数据库·c++·sqlite
leaves falling17 分钟前
C++类和对象(3)(初始化列表,类型转换,static成员,友元)
java·开发语言·c++
宵时待雨18 分钟前
C++笔记归纳15:封装map & set
开发语言·数据结构·c++·笔记·算法
眼眸流转23 分钟前
LeetCode热题100(七)
算法·leetcode·c#
福楠33 分钟前
现代C++ | 右值引用 + std::move + noexcept
linux·c语言·开发语言·c++
阿Y加油吧42 分钟前
算法高频压轴题|滑动窗口最大值 + 最小覆盖子串,单调队列 + 滑动窗口双杀
数据结构·算法·leetcode
格林威43 分钟前
工业相机图像采集处理:从 RAW 数据到 AI 可读图像,附海康相机 C++实战代码
开发语言·c++·人工智能·数码相机·计算机视觉·c#·工业相机
闻道且行之1 小时前
libhv 安装与使用全流程教程
c++·http·socket·libhv·c/c++
旺仔.2911 小时前
顺序容器:forward list单链表 详解
数据结构·c++·list
txinyu的博客1 小时前
解析muduo源码之 HttpServer.h & HttpServer.cc
c++