Efficient data structure for fast random access, search, insertion and deletion

前端 未结 8 2103
灰色年华
灰色年华 2021-01-31 11:11

I\'m looking for a data structure (or structures) that would allow me keep me an ordered list of integers, no duplicates, with indexes and values in the same range.

I ne

相关标签:
8条回答
  • 2021-01-31 11:54

    Use a vector for the array access.

    Use a map as a search index to the subscript into the vector.

    • given a subscript fetch the value from the vector O(1)
    • given a key, use the map to find the subscript of the value. O(lnN)
    • insert a value, push back on the vector O(1) amortized, insert the subscript into the map O(lnN)
    • delete a value, delete from the map O(lnN)
    0 讨论(0)
  • 2021-01-31 11:58

    How about using a sorted array with binary search?

    Insertion and deletion is slow. but given the fact that the data are plain integers could be optimized with calls to memcpy() if you are using C or C++. If you know the maximum size of the array, you can even avoid any memory allocations during the usage of the array, as you can preallocate it to the maximum size.

    The "best" approach depends on how many items you need to store and how often you will need to insert/delete compared to finding. If you rarely insert or delete a sorted array with O(1) access to the values is certainly better, but if you insert and delete things frequently a binary tree can be better than the array. For a small enough n the array most likely beats the tree in any case.

    If storage size is of concern, the array is better than the trees, too. Trees also need to allocate memory for every item they store and the overhead of the memory allocation can be significant as you only store small values (integers).

    You may want to profile what is faster, the copying of the integers if you insert/delete from the sorted array or the tree with it's memory (de)allocations.

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