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()];
    }
};
相关推荐
不会就选b4 小时前
C++补充部分(一)--lambda 表达式
开发语言·c++
lvwangshu12 小时前
方阵游戏 题解
题解·技巧·前缀优化·性质题·思维好题·推导题
丰色木夕12 小时前
Ubuntu22.04下源码编译安装USD-Brep
c++·ubuntu·nvidia·usd-brep
文丑颜不良啊12 小时前
LeetCode51~75题目解析
leetcode
学电子她就能回来吗13 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
衍玊15 小时前
多路转接原理与应用
c++
himobrinehacken16 小时前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
文丑颜不良啊17 小时前
LeetCode1~50题目解析
leetcode
Pniubi17 小时前
力扣146.LRU缓存机制
算法·leetcode·缓存
Android小码家19 小时前
Vehicle 实战 自定义属性+测试demo
java·c++·framework·vhal·vehicle