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()];
    }
};
相关推荐
小猪佩奇TONY5 分钟前
C++ 学习(3) ----设计模式
c++·学习·设计模式
Brookty17 分钟前
【算法】二分查找(一)朴素二分
java·学习·算法·leetcode·二分查找
黑色的山岗在沉睡1 小时前
LeetCode 2761. 和等于目标值的质数对
算法·leetcode·职场和发展
bawangtianzun1 小时前
重链剖分 学习记录
数据结构·c++·学习·算法
头发掉光的程序员2 小时前
第九章 纹理贴图
c++·图形渲染·direct12
T1an-15 小时前
力扣70.爬楼梯
算法·leetcode·职场和发展
T1an-15 小时前
力扣169.多数元素
数据结构·算法·leetcode
进击中的小龙6 小时前
在vscode下的cmake项目里传参调试c++命令行程序
c++·vscode
奔跑吧邓邓子8 小时前
【C++实战(74)】深入C++安全编程:密码学实战之旅
c++·安全·实战·密码学·安全编程
明天会有多晴朗9 小时前
C语言入门教程(第1讲):最通俗的C语言常见概念详解与实战讲解
c语言·开发语言·c++