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

难度: 困难

题目描述

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

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

  1. insert(val):向集合中插入元素 val。
  2. remove(val):当 val 存在时,从集合中移除一个 val。
  3. 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();

思路

与STL的unordered_multiset相比,多的要求是可以 O ( 1 ) O(1) O(1)时间完成随机获取一个元素,为了实现这个要求,可以把multiset中的每一个元素的迭代器都保存在一个vector中,为了保持删除的时间复杂度仍然为 O ( 1 ) O(1) O(1),还需要一个unordered_map将iter映射到index。
如果在插入multiset时导致了重哈希,那么一切的迭代器都会失效(引用不受影响),但是由于下面的代码定义的hash不可能重复,所以不会发生这种情况。

代码

class RandomizedCollection {
public:
    /** 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) {
        bool ret = vals.find(val) == vals.end();
        auto iter = vals.emplace(val);
        iters.push_back(iter);
        iter2index.emplace(iter, iters.size() - 1);
        return ret;
    }

    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        auto iter = vals.find(val);
        if (iter != vals.end()) {
            vals.erase(iter);
            int index = iter2index[iter];
            iters[index] = *iters.rbegin();
            iter2index[iters[index]] = index;
            iters.pop_back();
            return true;
        } else return false;
    }

    /** Get a random element from the collection. */
    int getRandom() {
        return *iters[rand() % iters.size()];
    }
    
private:
    struct hash {
        size_t operator()(const unordered_multiset<int>::iterator &iter) const {
            return size_t(&(*iter));  // 通过迭代器找到元素的地址,将其作为哈希值,不可能重复
        }
    };

    unordered_multiset<int> vals;
    vector<unordered_multiset<int>::iterator> iters;
    unordered_map<unordered_multiset<int>::iterator, int, hash> iter2index;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值