Insert Delete GetRandom O(1) 常數時間插入、刪除和獲取隨機元素
阿新 • • 發佈:2018-12-13
設計一個支援在平均 時間複雜度 O(1) 下,執行以下操作的資料結構。
insert(val)
:當元素 val 不存在時,向集合中插入該項。remove(val)
:元素 val 存在時,從集合中移除該項。getRandom
:隨機返回現有集合中的一項。每個元素應該有相同的概率被返回。
示例 :
// 初始化一個空的集合。 RandomizedSet randomSet = new RandomizedSet(); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。 randomSet.insert(1); // 返回 false ,表示集合中不存在 2 。 randomSet.remove(2); // 向集合中插入 2 。返回 true 。集合現在包含 [1,2] 。 randomSet.insert(2); // getRandom 應隨機返回 1 或 2 。 randomSet.getRandom(); // 從集合中移除 1 ,返回 true 。集合現在包含 [2] 。 randomSet.remove(1); // 2 已在集合中,所以返回 false 。 randomSet.insert(2); // 由於 2 是集合中唯一的數字,getRandom 總是返回 2 。 randomSet.getRandom();
思路:這道題難點在於所有的操作都要求O(1)的時間,所以單純的unordered_set是無法完成的,看了discuss部分發現有個很巧的方法,需要兩個輔助結構hashmap和一個vector,其中hashmap的說明如下,hashmap<key=vector下標對應的數值,value=下標>,即我們可以通過m[數值]找到對應vector的元素所在的下標。接下來具體說一下各個方法的操作:
insert操作:我們首先看hashmap中是否存在對應的key,如果有直接返回false,如果沒有就在vector的back處新增val,並把key=val,value=(vector.size()-1)新增到hashmap中。
delete操作:同理先檢視hashmap中是否存在對應的key,如果沒有直接返回false,然後交換nums中的val值(待刪除元素)和nums的末尾值,怎麼刪除呢?其實就是類似A-B交換法,核心程式碼如下:
bool remove(int val) {
if (m.find(val) == m.end()) return false;
int last = nums.back();
m[last] = m[val];
nums[m[val]] = last;
nums.pop_back();
m.erase(val);
return true;
}
基本思想是對於nums而言,先進行下標交換,在進行值交換,大家debug一下就明白了。
getRandon操作:其實就返回nums.size()裡的任意一個值即可。
參考程式碼:
class RandomizedSet {
public:
/** Initialize your data structure here. */
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (m.find(val) != m.end()) return false;
nums.push_back(val);
m[val] = (nums.size() - 1);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (m.find(val) == m.end()) return false;
int last = nums.back();
m[last] = m[val];
nums[m[val]] = last;
nums.pop_back();
m.erase(val);
return true;
}
/** Get a random element from the set. */
int getRandom() {
return nums[rand() % nums.size()];
}
private:
vector<int> nums;
unordered_map<int, int> m;
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* bool param_1 = obj.insert(val);
* bool param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/