Problem: I need to get a random item for a container, and also remove it from this container. The container does not need to be sorted. I do not care about the order.
- A vector can get a random element in
O(1), but delete it only inO(N) - The list removes the item in
O(1), but can only get a random item inO(N)
So, I came up with the idea of creating a custom vector that will allow you to remove any element by its index using complexity O(1)+. The idea is to swap the last item and the item you want to delete, then pop_back(). If you need to remove the last item - simply pop_back(). The order of the vector will not be the same, but you get a quick delete method.
As I can understand, deque has slower index access and worse delete complexity, then my solution, but I'm not 100% sure.
I am curious if there are data structures that have random access and deletion of elements in O(1)either O(logN)index or mb by value?
Stals source
share