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()];
    }
};
相关推荐
橘颂TA13 分钟前
【剑斩OFFER】算法的暴力美学——除自身以外数组的乘积
算法·leetcode·职场和发展·结构与算法
鑫—萍40 分钟前
C/C++精品算法——双指针(1)
c语言·c++·算法
2501_941111891 小时前
低延迟系统C++优化
开发语言·c++·算法
2501_941111992 小时前
C++中的装饰器模式变体
开发语言·c++·算法
怕什么真理无穷2 小时前
C++_面试15_零拷贝
c++·面试·职场和发展
Espresso Macchiato2 小时前
Leetcode 3748. Count Stable Subarrays
算法·leetcode·职场和发展·leetcode hard·leetcode 3748·leetcode周赛476·区间求和
AA陈超2 小时前
ASC学习笔记0007:用于与GameplayAbilities系统交互的核心ActorComponent
c++·笔记·学习·ue5·虚幻引擎
大袁同学2 小时前
【哈希hash】:程序的“魔法索引”,实现数据瞬移
数据结构·c++·算法·哈希算法·散列表
沐怡旸3 小时前
【穿越Effective C++】条款21:必须返回对象时,别妄想返回其reference——对象返回的语义与效率平衡
c++·面试