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()];
    }
};
相关推荐
y = xⁿ19 分钟前
20天速通LeetCode day08:关于栈
算法·leetcode·职场和发展
aq553560020 分钟前
PHP vs C++ vs 易语言:编程语言终极对比
开发语言·c++·php
tankeven38 分钟前
HJ181 相差不超过k的最多数
数据结构·c++·算法
XWalnut1 小时前
LeetCode刷题 day13
数据结构·算法·leetcode
AlbertS1 小时前
distcc + ccache 编译递归问题排查总结
c++·cmake·gcc·g++·distcc·ccache
小苗卷不动1 小时前
ps axj | grep 和 which命令
c++
云泽8082 小时前
第十五届蓝桥杯大赛软件赛省赛C/C++大学B组
c语言·c++·算法·蓝桥杯
Wadli2 小时前
集群C++聊天服务器
服务器·开发语言·c++
洛水水2 小时前
# 线程池详解:从原理到实现
c++·线程池
思麟呀2 小时前
HTTP的Cookie和Session
linux·网络·c++·网络协议·http