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()];
    }
};
相关推荐
song439994 分钟前
C++——矩阵无重复行列取数问题
开发语言·c++·矩阵
黑不溜秋的16 分钟前
C++ 在项目中使用Git
开发语言·c++·git
小无名呀44 分钟前
C++初阶:类和对象(上)
开发语言·c++
NeVeRMoRE_20241 小时前
【数据结构和算法实践-树-LeetCode110-平衡二叉树】
数据结构·b树·算法·leetcode
湫兮之风2 小时前
C++:opencv计算轮廓周长--cv::arcLength
开发语言·c++·opencv
一只邪恶大泡2 小时前
力扣14.最长公共前缀
数据结构·算法·leetcode
ya888g2 小时前
C++ STL 数据结构 vector基本用法
开发语言·数据结构·c++
是小Y啦3 小时前
leetcode 146.LRU缓存
算法·leetcode·缓存
wxy20243153 小时前
连年(年份)
c语言·c++·算法
LuckyRich13 小时前
【高阶数据结构】跳表
开发语言·数据结构·c++