/
380. Insert Delete GetRandom O(1) 2.cpp
60 lines (48 loc) · 1.24 KB
/
380. Insert Delete GetRandom O(1) 2.cpp
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
// https://leetcode.com/problems/insert-delete-getrandom-o1/
class RandomizedSet
{
unordered_map<int, int> position;
vector<int> vals;
public:
RandomizedSet()
{
}
bool insert(int val)
{
if (position.find(val) != position.end())
return false;
vals.push_back(val);
position[val] = vals.size() - 1;
return true;
}
bool remove(int val)
{
if (position.find(val) == position.end())
return false;
int valToRemovePosition = position[val];
int lastValPosition = vals.size() - 1;
position[vals[lastValPosition]] = valToRemovePosition;
swap(valToRemovePosition, lastValPosition);
vals.pop_back();
position.erase(val);
return true;
}
int getRandom()
{
int randomPosition = rand() % vals.size();
return vals[randomPosition];
}
void swap(int i, int j)
{
int temp = vals[i];
vals[i] = vals[j];
vals[j] = temp;
}
};
/**
* 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();
*/