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()];
    }
};
相关推荐
D_evil__4 小时前
【Effective Modern C++】第三章 转向现代C++:16. 让const成员函数线程安全
c++
Queenie_Charlie5 小时前
前缀和的前缀和
数据结构·c++·树状数组
kokunka6 小时前
【源码+注释】纯C++小游戏开发之射击小球游戏
开发语言·c++·游戏
_不会dp不改名_7 小时前
leetcode_3010 将数组分成最小总代价的子数组 I
算法·leetcode·职场和发展
John_ToDebug8 小时前
浏览器内核崩溃深度分析:从 MiniDump 堆栈到 BindOnce UAF 机制(未完待续...)
c++·chrome·windows
txinyu的博客9 小时前
解析muduo源码之 SocketsOps.h & SocketsOps.cc
c++
ctyshr10 小时前
C++编译期数学计算
开发语言·c++·算法
努力写代码的熊大10 小时前
c++异常和智能指针
java·开发语言·c++
John_ToDebug10 小时前
WebContent 与 WebView:深入解析浏览器渲染架构的双层设计
c++·chrome·ui
千秋乐。10 小时前
C++-string
开发语言·c++