39 lines
711 B
C++
39 lines
711 B
C++
#include <cstdlib>
|
|
#include <ctime>
|
|
#include <unordered_map>
|
|
#include <vector>
|
|
|
|
class RandomizedSet {
|
|
public:
|
|
RandomizedSet() {
|
|
srand(time(nullptr));
|
|
}
|
|
|
|
bool insert(int val) {
|
|
if (map.find(val) != map.end()) return false;
|
|
map[val] = list.size();
|
|
list.push_back(val);
|
|
return true;
|
|
}
|
|
|
|
bool remove(int val) {
|
|
auto it = map.find(val);
|
|
if (it == map.end()) return false;
|
|
int idx = it->second;
|
|
int lastVal = list.back();
|
|
list[idx] = lastVal;
|
|
map[lastVal] = idx;
|
|
list.pop_back();
|
|
map.erase(it);
|
|
return true;
|
|
}
|
|
|
|
int getRandom() {
|
|
return list[rand() % list.size()];
|
|
}
|
|
|
|
private:
|
|
std::vector<int> list;
|
|
std::unordered_map<int, int> map;
|
|
};
|