Leetcode 381. O(1) 時間插入、刪除和獲取隨機元素 - 允許重複【哈希表[哈希表存儲每個元素在vector中的索引]+vector】

問題描述

設計一個支持在平均 時間複雜度 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();[1]^{[1]}

解題報告

我們並不關心元素的順序,所以可以使用動態數組在 O(1)O(1) 的時間執行 insert。

由於我們不關心元素的順序,如果我們想刪除第 i 個索引處的元素,我們可以交換第 i 個元素和最後一個元素,並執行 O(1)O(1)pop 操作(事實上我們不需要交換,我們只需要將最後一個元素複製到索引 i 中,再彈出最後一個元素)。

問題中最困難的部分就是要在 O(1)O(1) 的時間找到要刪除元素的索引。
答案是:通過一個哈希表將元素值映射到它們的索引 [2]^{[2]}

利用哈希結構 unordered_map<int, unordered_set<int> > value_indices 存儲值對應的下標集合 [3]^{[3]}

實現代碼

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) == 0;
        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) == 0) 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() {
        int s = nums.size();
        int r = rand() % s;
        return nums[r];
    }
};

// 作者:da-li-wang
// 鏈接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed/solution/c-ha-xi-ti-jie-by-da-li-wang-2/
// 來源:力扣(LeetCode)
// 著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

參考資料

[1] Leetcode 381. O(1) 時間插入、刪除和獲取隨機元素 - 允許重複
[2] 官方題解
[3] da-li-wang

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章