问题
I need a data structure that supports two operations - delete and search. Now, the delete operation should run in amortized O(1) time, while search should run in O(log n) time.
Search operation should work as follows: look for value specified and if it is here, return value itself. Otherwise, return the nearest greater value (return inorder successor).
What could this data structure be?
回答1:
It could be a pair of data structures:
- binary search tree, holding values
- hash table, holding pointers to nodes in binary search tree
When you want to search, do the search in binary search tree in O(log n) time. When you want to delete, first find the node in hash table in amortized O(1) and delete in binary search tree in amortized O(1).
回答2:
If your range is reasonably bound at m
, you could implement a Y-fast trie. This supports delete and search for successor in O(log log m)
time and takes O(n)
space.
You could also use k
tries with the same m
as buckets with offsets, to represent the range km
.
If the number of deletions is small compared to the range, save only the deletions rather than the available numbers.
回答3:
Another solution is to start with a hash set that is initially empty. When somebody requests a delete, add that value to the hash set. That's O(1).
There are several ways to proceed after that.
- When searching for items, if you encounter a node whose value is in the hash set, mark it as deleted and continue the search. You never remove anything from the tree, but nodes that are marked as deleted are no longer "found." You just return the inorder successor.
- When you find an item that was searched for, check the hash set to see if the item was supposed to be deleted. Delete the item and return its inorder successor.
- When searching the tree, whenever you run across a node whose value is in the hash set, delete the node and continue the search.
Of course, you'd remove the value from the hash set whenever you marked a node as deleted or removed a node from the tree.
All three of those give you O(log n) search, and amortize the cost of deletions as part of the search process.
来源:https://stackoverflow.com/questions/49251690/data-structure-with-amortized-o1-delete-and-olog-n-search