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()];
    }
};
相关推荐
头发还没掉光光6 小时前
Linux网络初始及网络通信基本原理
linux·运维·开发语言·网络·c++
橘颂TA6 小时前
【剑斩OFFER】算法的暴力美学——二分查找
算法·leetcode·面试·职场和发展·c/c++
m0_748248026 小时前
揭开 C++ vector 底层面纱:从三指针模型到手写完整实现
开发语言·c++·算法
海盗猫鸥6 小时前
「C++」string类(2)常用接口
开发语言·c++
序属秋秋秋6 小时前
《Linux系统编程之开发工具》【实战:倒计时 + 进度条】
linux·运维·服务器·c语言·c++·ubuntu·系统编程
还是码字踏实7 小时前
基础数据结构之哈希表:两数之和(LeetCode 1 简单题)
数据结构·leetcode·散列表
Kt&Rs7 小时前
11.5 LeetCode 题目汇总与解题思路
数据结构·算法·leetcode
还是码字踏实7 小时前
基础数据结构之数组的前缀和技巧:和为K的子数组(LeetCode 560 中等题)
算法·leetcode·前缀和·哈希字典
py有趣12 小时前
LeetCode算法学习之两数之和 II - 输入有序数组
学习·算法·leetcode
夏鹏今天学习了吗12 小时前
【LeetCode热题100(62/100)】搜索二维矩阵
算法·leetcode·矩阵