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()];
    }
};
相关推荐
sin_hielo6 分钟前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi12 分钟前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表
py有趣13 分钟前
LeetCode算法学习之数组中的第K个最大元素
学习·算法·leetcode
吗~喽13 分钟前
【LeetCode】将 x 减到 0 的最小操作数
算法·leetcode
cookies_s_s38 分钟前
C++20 协程
linux·开发语言·c++
hetao17338371 小时前
2025-11-13~14 hetao1733837的刷题记录
c++·算法
hansang_IR1 小时前
【题解】洛谷 P2476 [SCOI2008] 着色方案 [记搜]
c++·算法·记忆化搜索
AA陈超2 小时前
ASC学习笔记0010:效果被应用时的委托
c++·笔记·学习
AA陈超2 小时前
ASC学习笔记0004:通知相关方能力规格已被修改
c++·笔记·学习·游戏·ue5·游戏引擎·虚幻
阿巴~阿巴~2 小时前
IPv4地址转换函数详解及C++容器安全删除操作指南
linux·服务器·c++·网络协议·算法·c++容器安全删除操作·ipv4地址转换函数