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()];
    }
};
相关推荐
xiaoye-duck7 分钟前
《算法题讲解指南:动态规划算法--子数组系列》--21.乘积最大子数组,22.乘积为正数的最长子数组
c++·算法·动态规划
计算机安禾9 分钟前
【数据结构与算法】第24篇:哈夫曼树与哈夫曼编码
c语言·开发语言·数据结构·c++·算法·visual studio
wsoz9 分钟前
Leetcode双指针-day2
算法·leetcode
郝学胜-神的一滴35 分钟前
[力扣 20] 栈解千愁:有效括号序列的优雅实现与深度解析
java·数据结构·c++·算法·leetcode·职场和发展
代码改善世界35 分钟前
【C++初阶】手撕C++ string类
java·开发语言·c++
君鼎37 分钟前
C++14 新特性全面总结
c++
AlenTech44 分钟前
128. 最长连续序列 - 力扣(LeetCode)
算法·leetcode·职场和发展
田梓燊1 小时前
leetcode 无重复字符的最长子串
算法·leetcode·职场和发展
ShineWinsu1 小时前
MySQL主从延迟根因诊断法技术文章大纲
c++
tankeven1 小时前
HJ160 迷宫
c++·算法