跳到主要内容

380 O(1) 时间插入、删除和获取随机元素

https://leetcode.cn/leetbook/read/top-interview-questions-medium/xw5rt1/

cost: 15m58s

class RandomizedSet {
public:
RandomizedSet() {
std::random_device rd;
this->gen = std::mt19937(rd());
}

bool insert(int val) {
if (m.count(val)) {
return false;
}
vec.push_back(val);
m[val] = vec.size() - 1;
return true;
}

bool remove(int val) {
if (!m.count(val)) {
return false;
}
int idx = m[val];
std::swap(vec[idx], vec[vec.size() - 1]);
m[vec[idx]] = idx;
vec.pop_back();
m.erase(val);
return true;
}

int getRandom() {
std::uniform_int_distribution<> dis(0, vec.size() - 1);
int idx = dis(this->gen);
return vec[idx];
}

private:
unordered_map<int, int> m;
vector<int> vec;
std::mt19937 gen;
};

/**
* 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();
*/