-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_0380_RandomizedSet.cc
More file actions
71 lines (63 loc) · 1.39 KB
/
Problem_0380_RandomizedSet.cc
File metadata and controls
71 lines (63 loc) · 1.39 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <random>
#include <unordered_map>
#include <vector>
using namespace std;
class RandomizedSet
{
private:
unordered_map<int, int> keyIndexMap;
unordered_map<int, int> indexKeyMap;
int size;
public:
RandomizedSet() { size = 0; }
bool insert(int val)
{
if (!keyIndexMap.count(val))
{
keyIndexMap.emplace(val, size);
indexKeyMap.emplace(size++, val);
return true;
}
return false;
}
bool remove(int val)
{
if (keyIndexMap.count(val))
{
int deleteIndex = keyIndexMap.at(val);
int lastIndex = --size;
int lastKey = indexKeyMap.at(lastIndex);
keyIndexMap[lastKey] = deleteIndex;
indexKeyMap[deleteIndex] = lastKey;
keyIndexMap.erase(val);
indexKeyMap.erase(lastIndex);
return true;
}
return false;
}
int random(int min, int max)
{
random_device seed;
ranlux48 engine(seed());
uniform_int_distribution<> distrib(min, max);
int res = distrib(engine);
return res;
}
int getRandom()
{
if (size == 0)
{
return -1;
}
int randomIndex = random(0, size - 1);
return indexKeyMap.at(randomIndex);
}
};
/**
* 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();
*/