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()];
    }
};
相关推荐
liulilittle2 小时前
FileStream C++
开发语言·c++·cocoa
Gomiko2 小时前
C/C++基础(五):分支
c语言·c++
点PY2 小时前
C++ 中 std::async 和 std::future 的并发性
java·开发语言·c++
不会代码的小猴2 小时前
C++的第九天笔记
开发语言·c++·笔记
fqbqrr3 小时前
2512C++,clangd支持模块
开发语言·c++
老王熬夜敲代码5 小时前
C++中的thread
c++·笔记·面试
鹿角片ljp5 小时前
力扣140.快慢指针法求解链表倒数第K个节点
算法·leetcode·链表
qq_479875435 小时前
C++ 鸭子类型” (Duck Typing)
开发语言·c++
崇山峻岭之间5 小时前
C++ Prime Plus 学习笔记033
c++·笔记·学习
暗然而日章6 小时前
C++基础:Stanford CS106L学习笔记 7 类
c++·笔记·学习