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()];
    }
};
相关推荐
m0_706653233 分钟前
分布式系统安全通信
开发语言·c++·算法
Zach_yuan18 分钟前
深入浅出 JSONCpp
linux·服务器·网络·c++
寻寻觅觅☆35 分钟前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
lightqjx1 小时前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
alphaTao1 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习1 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
阿猿收手吧!1 小时前
【C++】string_view:高效字符串处理指南
开发语言·c++
不知名XL2 小时前
day50 单调栈
数据结构·算法·leetcode
Word码2 小时前
[C++语法] 继承 (用法详解)
java·jvm·c++
@––––––2 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划