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()];
    }
};
相关推荐
C+++Python4 分钟前
C++ 进阶学习完整指南
java·c++·学习
sparEE22 分钟前
c++值类别、右值引用和移动语义
开发语言·c++
jrrz08281 小时前
Apollo MPC Controller
c++·自动驾驶·apollo·mpc·横向控制·lateral control
小王C语言3 小时前
【线程概念与控制】:线程封装
jvm·c++·算法
圣保罗的大教堂3 小时前
leetcode 796. 旋转字符串 简单
leetcode
学习,学习,在学习3 小时前
Qt工控仪器程序框架设计详解(工控多仪器控制版本)
开发语言·c++·qt
信竞星球_少儿编程题库4 小时前
2026年全国信息素养大赛算法应用主题赛 丝路新城 C++ 模拟卷(三)
开发语言·c++
Zhang~Ling4 小时前
深入解析C++list:从0到1实现一个完整的链表类
c++·链表·list
z200509304 小时前
今日算法(依旧二叉树)
算法·leetcode·职场和发展
王老师青少年编程5 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串综合】:[NOIP 2015 提高组] 子串
c++·字符串·csp·高频考点·子串·信奥赛