Leetcode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复 C++

    技术2024-07-16  80

    Leetcode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复

    题目

    设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。

    注意: 允许出现重复元素。

    insert(val):向集合中插入元素 val。 remove(val):当 val 存在时,从集合中移除一个 val。 getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。

    示例:

    // 初始化一个空的集合。 RandomizedCollection collection = new RandomizedCollection(); // 向集合中插入 1 。返回 true 表示集合不包含 1 。 collection.insert(1); // 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。 collection.insert(1); // 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。 collection.insert(2); // getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。 collection.getRandom(); // 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。 collection.remove(1); // getRandom 应有相同概率返回 1 和 2 。 collection.getRandom();

    题解

    总体思路与380题一致,只不过这里元素可能重复,因此我们存下标位置时要存到容器当中

    代码

    class RandomizedCollection { public: vector<int> nums; unordered_map<int,unordered_set<int>> numsIndex; int size; /** Initialize your data structure here. */ RandomizedCollection() { size = 0; } /** 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); numsIndex[val].insert(size); size++; return numsIndex[val].size() == 1; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { if(numsIndex.count(val) == 0) return false; int last = nums.back(); int id=size-1; if(last != val){ //如果删除的数就在数组最后,可以不用进行替换 id = *(numsIndex[val].begin()); numsIndex[last].erase(size-1); numsIndex[last].insert(id); nums[id] = last; } nums.pop_back(); size--; numsIndex[val].erase(id); if(numsIndex[val].empty()) numsIndex.erase(val); return true; } /** Get a random element from the collection. */ int getRandom() { return nums[random() %size]; } }; /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection* obj = new RandomizedCollection(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    Processed: 0.011, SQL: 9