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()];
    }
};
相关推荐
什巳21 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
从零开始的代码生活_1 天前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端
鱼儿也有烦恼1 天前
快速学完 LeetCode top 1~50
leetcode·algorithm
aaPIXa6221 天前
C++ 用 13 条规则让模型写出安全现代 C++
java·c++·安全
枕星而眠1 天前
【数据结构】红黑树入门指南
运维·数据结构·c++·后端
2601_949817721 天前
C++指针与引用深度精讲:底层原理、差异对比与高阶实战陷阱
java·jvm·c++
烟锁池塘柳01 天前
【C/C++】解决C++控制台输出中文乱码问题
c语言·开发语言·c++
zh路西法1 天前
【10天速通Navigation2】(九):LQR最优控制器的原理推导与Nav2插件实现
c++·ros2·最优控制·lqr·navigation2
退休倒计时1 天前
【每日一题】LeetCode 17. 电话号码的字母组合 TypeScript
算法·leetcode·typescript
粘稠的浆糊1 天前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法