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()];
    }
};
相关推荐
yyds_yyd_100861 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
库克克3 小时前
【C++】set 与multiset
开发语言·c++
Mortalbreeze3 小时前
深入 Linux Socket 编程:端口号、网络字节序与 struct sockaddr 详解
linux·服务器·网络·c++
玖玥拾4 小时前
LeetCode 26 删除有序数组中的重复项
算法·leetcode
繁星蓝雨5 小时前
C++设计原理——异常处理
java·c++·异常处理·noexcept·throw·try catch
Kurisu_红莉栖5 小时前
关于相关问题的自我回答
c++
hansang_IR5 小时前
【题解】[AGC020E] Encoding Subsets
c++·算法·dp
我不管我就要叫小猪6 小时前
C/C++----命名空间
c语言·开发语言·c++
白白白小纯6 小时前
算法篇—返回倒数第k个节点
c语言·数据结构·算法·leetcode
无忧.芙桃7 小时前
数据结构之堆
c语言·数据结构·c++·算法·