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()];
    }
};
相关推荐
纵有疾風起42 分钟前
C++——类和对象(3)
开发语言·c++·经验分享·开源
承渊政道2 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
孤独得猿2 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd
new coder2 小时前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
无敌最俊朗@3 小时前
数组-力扣hot56-合并区间
数据结构·算法·leetcode
哼?~4 小时前
C++11标准 上 (万字解析)
开发语言·c++
码农多耕地呗4 小时前
力扣94.二叉树的中序遍历(递归and迭代法)(java)
数据结构·算法·leetcode
给大佬递杯卡布奇诺4 小时前
FFmpeg 基本API avformat_alloc_context 函数内部调用流程分析
c++·ffmpeg·音视频
微笑尅乐4 小时前
BFS 与 DFS——力扣102.二叉树的层序遍历
leetcode·深度优先·宽度优先
楼田莉子4 小时前
C++学习:C++11扩展:constexpr特性
开发语言·c++·学习