跳转至

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

题目描述*

标签*

哈希表;

思路 & 代码*

O(1) 就哈希表,每个键值存对应的个数,删除就个数 -1。要实现与个数相关的随机,那似乎还得把所有元素存起来,然后随机下标,这种是最简单的。同时还要保证 O(1) 的删除复杂度。。。好麻烦。直接看题解了。。。

思路差不多,主要还是从 vector 中删除元素的操作,通过与尾元素交换保证时间复杂度 O(1)

class RandomizedCollection {
public:
    unordered_map<int, unordered_set<int> > value_indices;
    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) {
        bool res = !value_indices.count(val);
        nums.push_back(val);
        value_indices[val].insert(nums.size() - 1);
        return res;
    }

    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        if (!value_indices.count(val)) { 
            return false;
        }
        int tail = nums.back();
        if (tail == val) {
            value_indices[val].erase(nums.size() - 1);
            nums.pop_back();
        } else {
            int ind = *value_indices[val].begin();
            nums[ind] = tail;
            value_indices[tail].erase(nums.size() - 1);
            value_indices[tail].insert(ind);
            value_indices[val].erase(ind);
            nums.pop_back();
        }
        if (value_indices[val].empty()) {
            value_indices.erase(val);
        }
        return true;
    }

    /** Get a random element from the collection. */
    int getRandom() {
        return nums[rand() % nums.size()];
    }
};

最后更新: July 23, 2022