Data structure with amortized O(1) delete and O(log n) search

萝らか妹 提交于 2021-02-07 08:29:29

问题


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.

  1. 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.
  2. 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.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!