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()];
    }
};
相关推荐
dying_man12 分钟前
LeetCode--42.接雨水
算法·leetcode
笑鸿的学习笔记17 分钟前
qt-C++语法笔记之Stretch与Spacer的关系分析
c++·笔记·qt
hardStudy_h31 分钟前
C++——内联函数与Lambda表达式
开发语言·jvm·c++
ZZZS05161 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
黑听人1 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode
位东风2 小时前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式
前端拿破轮4 小时前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
雷羿 LexChien4 小时前
C++内存泄漏排查
开发语言·c++
嘉小华4 小时前
CMake 完全指南:第一章 - 构建的烦恼 - 为什么需要CMake?
c++
Feliz Da Vida4 小时前
[代码学习] c++ 通过H矩阵快速生成图像对应的mask
c++·学习