-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertDeleteGetrandomO1.cpp
More file actions
43 lines (36 loc) · 1.1 KB
/
Copy pathinsertDeleteGetrandomO1.cpp
File metadata and controls
43 lines (36 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <vector>
#include <unordered_map>
#include <random>
using namespace std;
class RandomizedSet {
private:
unordered_map<int, int> valToIndex;
vector<int> values;
mt19937 gen;
public:
RandomizedSet() : gen(random_device{}()) {}
bool insert(int val) {
if (valToIndex.count(val)) { return false;}
values.push_back(val);
valToIndex[val] = values.size() - 1;
return true;
}
bool remove(int val) {
if (!valToIndex.count(val)) { return false;}
int index = valToIndex.at(val);
// Move the last element to the position of the element to remove
values[index] = values[values.size() - 1];
// Update the index of the element that was moved
valToIndex[values[index]] = index;
// Remove the last element from the vector
values.pop_back();
// Remove the element from the map
valToIndex.erase(val);
return true;
}
int getRandom() {
uniform_int_distribution<int> dist(0, values.size() - 1);
return values[dist(gen)];
}
};