forked from s7917/Hacktoberfest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path380. Insert Delete GetRandom O(1).cpp
73 lines (52 loc) · 1.21 KB
/
380. Insert Delete GetRandom O(1).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
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<bits/stdc++.h>
using namespace std;
class myStructure
{
vector <int> arr;
unordered_map <int, int> Map;
public:
void add(int x)
{
if(Map.find(x) != Map.end())
return;
int index = arr.size();
arr.push_back(x);
Map.insert(std::pair<int,int>(x, index));
}
void remove(int x)
{
if(Map.find(x) == Map.end())
return;
int index = Map.at(x);
Map.erase(x);
int last = arr.size() - 1;
swap(arr[index], arr[last]);
arr.pop_back();
Map.at(arr[index]) = index;
}
int search(int x)
{
if(Map.find(x) != Map.end())
return Map.at(x);
return -1;
}
int getRandom()
{
srand (time(NULL));
int random_index = rand() % arr.size();
return arr.at(random_index);
}
};
int main()
{
myStructure ds;
ds.add(10);
ds.add(900);
ds.add(79);
ds.add(490);
cout << ds.search(900) << endl;
ds.remove(900);
ds.add(50);
cout << ds.search(50) << endl;
cout << ds.getRandom() << endl;
}