Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - C++ - 380. Insert Delete GetRandom O(1)
參考資訊:
https://www.cnblogs.com/grandyang/p/5740864.html
題目:

解答:
class RandomizedSet {
private:
vector<int> nums;
unordered_map<int, int> mp;
public:
RandomizedSet() {
}
bool insert(int val) {
if (mp.count(val)) {
return false;
}
nums.push_back(val);
mp[val] = nums.size() - 1;
return true;
}
bool remove(int val) {
if (!mp.count(val)) {
return false;
}
int idx = mp[val];
int last = nums.back();
nums[idx] = last;
mp[last] = idx;
nums.pop_back();
mp.erase(val);
return true;
}
int getRandom() {
return nums[rand() % nums.size()];
}
};
/**
* 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();
*/