We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent df8520d commit 2385d42Copy full SHA for 2385d42
0380-insert-delete-getrandom-o1.cpp
@@ -16,7 +16,7 @@ class RandomizedSet {
16
17
bool insert(int val) {
18
if (map.find(val) != map.end()) return false;
19
- map[val] = arr.size();
+ map[val] = arr.size(); // store index of val in arr
20
arr.push_back(val);
21
return true;
22
}
@@ -29,6 +29,11 @@ class RandomizedSet {
29
arr.erase(arr.end() - 1);
30
31
32
+ /*
33
+ remove val from arr in constant time:
34
+ since we don't care about the order of the elements in arr,
35
+ we can just swap val with the last element and then pop_back
36
+ */
37
map[arr.back()] = pos;
38
swap(arr[pos], arr.back());
39
0 commit comments