Skip to content

Commit 5163e15

Browse files
authored
Create insert-delete-getrandom-o1.cpp
1 parent 81620ca commit 5163e15

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

C++/insert-delete-getrandom-o1.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Time: O(1)
2+
// Space: O(n)
3+
4+
class RandomizedSet {
5+
public:
6+
/** Initialize your data structure here. */
7+
RandomizedSet() {
8+
9+
}
10+
11+
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
12+
bool insert(int val) {
13+
if (used_.count(val)) {
14+
return false;
15+
}
16+
17+
set_.emplace_back(val);
18+
used_[val] = set_.size() - 1;
19+
20+
return true;
21+
}
22+
23+
/** Removes a value from the set. Returns true if the set contained the specified element. */
24+
bool remove(int val) {
25+
if (!used_.count(val)) {
26+
return false;
27+
}
28+
29+
used_[set_.back()] = used_[val];
30+
swap(set_[used_[val]], set_.back());
31+
32+
used_.erase(val);
33+
set_.pop_back();
34+
35+
return true;
36+
}
37+
38+
/** Get a random element from the set. */
39+
int getRandom() {
40+
return set_[rand() % set_.size()];
41+
}
42+
43+
private:
44+
vector<int> set_;
45+
unordered_map<int, int> used_;
46+
};
47+
48+
/**
49+
* Your RandomizedSet object will be instantiated and called as such:
50+
* RandomizedSet obj = new RandomizedSet();
51+
* bool param_1 = obj.insert(val);
52+
* bool param_2 = obj.remove(val);
53+
* int param_3 = obj.getRandom();
54+
*/
55+

0 commit comments

Comments
 (0)