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()];
    }
};
相关推荐
源远流长jerry33 分钟前
STM32之MCU和GPIO
linux·c++·stm32·单片机·嵌入式硬件
汤永红1 小时前
week2-[一维数组]最大元素
数据结构·c++·算法·信睡奥赛
Minecraft红客4 小时前
C++小游戏荒芜的城堡
c++·游戏·娱乐
scx2013100410 小时前
20250814 最小生成树和重构树总结
c++·算法·最小生成树·重构树
weixin_3077791312 小时前
VS Code配置MinGW64编译SQLite3库
开发语言·数据库·c++·vscode·算法
无聊的小坏坏12 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
励志不掉头发的内向程序员13 小时前
STL库——string(类函数学习)
开发语言·c++
浮灯Foden15 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
淡海水15 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
执子手 吹散苍茫茫烟波17 小时前
leetcode415. 字符串相加
java·leetcode·字符串