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()];
    }
};
相关推荐
土司大王2 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
zander2584 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
程序员与背包客_CoderZ4 小时前
高性能分布式KV存储引擎RocksDB入门与C/C++编码实战
c语言·开发语言·数据库·c++·分布式·分布式数据库·rocksdb
进击的_鹏4 小时前
从零开始的 Redis 学习
服务器·数据库·c++·redis·缓存
欧叶冲冲冲4 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
圣保罗的大教堂5 小时前
leetcode 3622. 判断整除性 简单
leetcode
_Narcissus_5 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
布莱克6055 小时前
C++拷贝构造与拷贝赋值运算符的区别详解
开发语言·c++
Lyyaoo.5 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
啦啦啦啦啦zzzz6 小时前
时间轮定时器
linux·服务器·网络·c++·定时器