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()];
    }
};
相关推荐
chbmvdd7 小时前
week5题解
数据结构·c++·算法
vir027 小时前
小齐的技能团队(dp)
数据结构·c++·算法·图论
月夜的风吹雨7 小时前
【C++红黑树】:自平衡二叉搜索树的精妙实现
开发语言·c++·红黑树
讨厌下雨的天空7 小时前
Linux信号
linux·运维·c++
赖small强7 小时前
【Linux C/C++开发】第26章:系统级综合项目理论
linux·c语言·c++
程序猿小白日记8 小时前
走向智能化:从编程语言看人工智能的未来
leetcode
fpcc8 小时前
跟我学C++中级篇——重载问题分析之函数模板重载的问题
c++
仟濹9 小时前
【C/C++】经典高精度算法 5道题 加减乘除「复习」
c语言·c++·算法
kk”9 小时前
C++ map
开发语言·c++
共享家95279 小时前
特殊类的设计
开发语言·c++