added randomizedset
This commit is contained in:
1 parent
ea3d15f694
commit
1bb417d151
8 files changed
+100
-1
No files matched your search
@@ -0,0 +1,38 @@
|
||||
#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;
|
||||
};
|
||||
Reference in new issue
Block a user