-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_380_InsertDeleteGetRandomO1.cpp
93 lines (73 loc) · 2.2 KB
/
_380_InsertDeleteGetRandomO1.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* Source - https://leetcode.com/problems/insert-delete-getrandom-o1/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
class RandomizedSet {
unordered_map<int, int> indexMap;
vector<int> data;
int index;
public:
/** Initialize your data structure here. */
RandomizedSet() {
indexMap.clear();
data.clear();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (indexMap.find(val) == indexMap.end()) {
data.push_back(val);
indexMap[val] = data.size() - 1;
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (indexMap.find(val) != indexMap.end()) {
int lastIndex = data.size() - 1;
if (data[lastIndex] != val) {
int temp = data[indexMap[val]];
data[indexMap[val]] = data[lastIndex];
data[lastIndex] = temp;
indexMap[data[indexMap[val]]] = indexMap[val];
}
data.pop_back();
indexMap.erase(val);
return true;
}
return false;
}
/** Get a random element from the set. */
int getRandom() {
int random = rand() % data.size();
return data[random];
}
};
int main()
{
RandomizedSet obj;
bool ins, del;
ins = obj.insert(1);
if (ins == true) cout<<"Inserted";
else cout<<"Already present";
cout<<endl;
del = obj.remove(2);
if (del == true) cout<<"Removed";
else cout<<"Not present";
cout<<endl;
ins = obj.insert(2);
if (ins == true) cout<<"Inserted";
else cout<<"Already present";
cout<<endl;
cout<<"Random: "<<obj.getRandom()<<endl;
del = obj.remove(1);
if (del == true) cout<<"Removed";
else cout<<"Not present";
cout<<endl;
ins = obj.insert(2);
if (ins == true) cout<<"Inserted";
else cout<<"Already present";
cout<<endl;
cout<<"Random: "<<obj.getRandom()<<endl;
}