Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 2385d42

Browse files
committed
explanation for 380
1 parent df8520d commit 2385d42

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

0380-insert-delete-getrandom-o1.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class RandomizedSet {
1616

1717
bool insert(int val) {
1818
if (map.find(val) != map.end()) return false;
19-
map[val] = arr.size();
19+
map[val] = arr.size(); // store index of val in arr
2020
arr.push_back(val);
2121
return true;
2222
}
@@ -29,6 +29,11 @@ class RandomizedSet {
2929
arr.erase(arr.end() - 1);
3030
return true;
3131
}
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+
*/
3237
map[arr.back()] = pos;
3338
swap(arr[pos], arr.back());
3439
arr.erase(arr.end() - 1);

0 commit comments

Comments
 (0)