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()];
    }
};
相关推荐
佑白雪乐5 分钟前
<LeetCode>二叉树前/中/后/层遍历**递归&&非递归**
算法·leetcode·深度优先
6Hzlia17 分钟前
【Hot 100 刷题计划】 LeetCode 279. 完全平方数 | C++ 动态规划 (完全背包)
c++·leetcode·动态规划
H Journey22 分钟前
C++ 11 新特性 统一初始化与与 std::initializer_list
c++·列表初始化
木子墨51626 分钟前
LeetCode 热题 100 精讲 | 动态规划进阶篇:最大子数组和 · 分割等和子集 · 最长公共子序列 · 打家劫舍 III
数据结构·c++·算法·leetcode·动态规划·力扣
li16709027031 分钟前
第十章:list
c语言·开发语言·数据结构·c++·算法·list·visual studio
‎ദ്ദിᵔ.˛.ᵔ₎34 分钟前
仿函数使用
c++
Z1Jxxx38 分钟前
C++ P1150 Peter 的烟
数据结构·c++·算法
是娇娇公主~38 分钟前
线程池:工作窃取线程池WorkingStealingPool
c++·线程池
CheerWWW39 分钟前
C++学习笔记——函数指针、Lambda表达式、谨慎使用using namespace std、命名空间
c++·笔记·学习
夜猫子ing40 分钟前
如何编写一个CMakelists文件
开发语言·c++