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()];
    }
};
相关推荐
lisanndesu6 分钟前
第十五届蓝桥杯 C++A组
c++·蓝桥杯
-Excalibur-33 分钟前
IP数据包在计算机网络传输的全过程
java·网络·c++·笔记·python·网络协议·智能路由器
alphaTao38 分钟前
LeetCode 每日一题 2026/3/16-2026/3/22
linux·windows·leetcode
空空潍38 分钟前
LeetCode力扣 hot100一刷完结
算法·leetcode
历程里程碑41 分钟前
41 .UDP -3 群聊功能实现:线程池助力多客户端通信
linux·开发语言·网络·数据结构·c++·网络协议·udp
lcreek41 分钟前
LeetCode 1162.地图分析
算法·leetcode·bfs
山栀shanzhi43 分钟前
【FFmpeg】是什么是未压缩的裸流?
c++·ffmpeg
不染尘.1 小时前
排序算法详解1
开发语言·数据结构·c++·算法·排序算法
Tisfy1 小时前
LeetCode 3567.子矩阵的最小绝对差:暴力模拟
leetcode·矩阵·题解·模拟·暴力