日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時間:2024/7/5 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复(vector + 哈希) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 1. 題目
    • 2. 解題

1. 題目

設(shè)計一個支持在平均 時間復(fù)雜度 O(1) 下, 執(zhí)行以下操作的數(shù)據(jù)結(jié)構(gòu)。

注意: 允許出現(xiàn)重復(fù)元素。

  • insert(val):向集合中插入元素 val。
  • remove(val):當(dāng) val 存在時,從集合中移除一個 val。
  • getRandom:從現(xiàn)有集合中隨機(jī)獲取一個元素。每個元素被返回的概率應(yīng)該與其在集合中的數(shù)量呈線性相關(guān)。

示例:

// 初始化一個空的集合。 RandomizedCollection collection = new RandomizedCollection();// 向集合中插入 1 。返回 true 表示集合不包含 1 。 collection.insert(1);// 向集合中插入另一個 1 。返回 false 表示集合包含 1 。集合現(xiàn)在包含 [1,1] 。 collection.insert(1);// 向集合中插入 2 ,返回 true 。集合現(xiàn)在包含 [1,1,2] 。 collection.insert(2);// getRandom 應(yīng)當(dāng)有 2/3 的概率返回 1 ,1/3 的概率返回 2 。 collection.getRandom();// 從集合中刪除 1 ,返回 true 。集合現(xiàn)在包含 [1,2] 。 collection.remove(1);// getRandom 應(yīng)有相同概率返回 1 和 2 。 collection.getRandom();

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

2. 解題

類似題目:LeetCode 380. 常數(shù)時間插入、刪除和獲取隨機(jī)元素(哈希+vector)

  • 本題有重復(fù)數(shù)字,用一個哈希set存儲同一數(shù)字的所有下標(biāo)
class RandomizedCollection {vector<int> arr;unordered_map<int, unordered_set<int>> m;//數(shù)字 - 對應(yīng)的下標(biāo)集合 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 flag = true;if(m.find(val) != m.end())//存在元素了flag = false;arr.push_back(val);//加入元素m[val].insert(arr.size()-1);//記錄位置return flag;}/** Removes a value from the collection. Returns true if the collection contained the specified element. */bool remove(int val) {if(m.find(val) == m.end())return false;int idx = *m[val].begin();//找到一個待刪元素的位置m[val].erase(m[val].begin());//刪除位置記錄if(m[val].empty())m.erase(val);int last = arr.back();//數(shù)組最后的元素,跟idx位置的元素交換m[last].insert(idx);//跟下一句順序不能變,如果是同一位置就會出錯m[last].erase(arr.size()-1); if(m[last].empty())m.erase(last);arr[idx] = last;//跟新idx位置的元素為 lastarr.pop_back();//last實際為要刪除的元素,pop刪除return true;}/** Get a random element from the collection. */int getRandom() {int idx = random() % arr.size();return arr[idx];} };

88 ms 26.5 MB


我的CSDN博客地址 https://michael.blog.csdn.net/

長按或掃碼關(guān)注我的公眾號(Michael阿明),一起加油、一起學(xué)習(xí)進(jìn)步!

總結(jié)

以上是生活随笔為你收集整理的LeetCode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复(vector + 哈希)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。