How to create a data structure with run time limits

后端 未结 1 1522
野的像风
野的像风 2021-01-15 06:13

I need to implement a data structure that supports insertion deletion and search in O(log(n)) and extracting a special object in O(1). My Data structure needs to hold vehic

相关标签:
1条回答
  • 2021-01-15 06:51

    A hash table will support insertion, deletion, and search in much better than O(log(n)). That's assuming that you never have to re-hash everything when you grow the table. The difficult part would be locating the "next" vehicle in O(1) time.

    Depending on the implementation, a min heap will give you between O(1) and O(log(n)) (amortized) insertion, and finding the minimum item is O(1). Deleting an item from the heap is an O(log(n)) operation, but finding an arbitrary item in the heap is more than O(log(n)).

    Were I to implement this, I'd use two separate data structures: a hash table and a min heap. The reasoning is that the hash table provides very fast insertion, deletion, and lookup, and the heap provides ordering based on service time. The only place where this doesn't meet your started requirements is in deleting a vehicle, because that requires searching the heap for an arbitrary item.

    Actually, it'd be possible, although probably messy, to combine the two data structures so that your hash table stores heap node objects (which have a reference to the actual data) rather than the actual data objects. As long as the heap node knows where it is in the heap (i.e. has a parent pointer as well as left and right child pointers), then you can use the hash table to find a node and remove that node from the heap.

    0 讨论(0)
提交回复
热议问题