insert, delete, max in O(1)

后端 未结 8 1009
北海茫月
北海茫月 2020-11-29 17:42

Can someone tell me which data structure supports insert/delete/maximum operation in O(1)?

相关标签:
8条回答
  • 2020-11-29 18:31

    This is a classical interview question, and is usually presented like this:

    Devise a stack-like data structure that does push, pop and min (or max) operations in O(1) time. There are no space constraints.

    The answer is, you use two stacks: the main stack, and a min (or max) stack.

    So for example, after pushing 1,2,3,4,5 onto the stack, your stacks would look like this:

    MAIN   MIN
    +---+  +---+
    | 5 |  | 1 |
    | 4 |  | 1 |
    | 3 |  | 1 |
    | 2 |  | 1 |
    | 1 |  | 1 |
    +---+  +---+
    

    However, if you were to push 5,4,3,2,1, the stacks would look like this:

    MAIN   MIN
    +---+  +---+
    | 1 |  | 1 |
    | 2 |  | 2 |
    | 3 |  | 3 |
    | 4 |  | 4 |
    | 5 |  | 5 |
    +---+  +---+
    

    For 5,2,4,3,1 you would have:

    MAIN   MIN
    +---+  +---+
    | 1 |  | 1 |
    | 3 |  | 2 |
    | 4 |  | 2 |
    | 2 |  | 2 |
    | 5 |  | 5 |
    +---+  +---+
    

    and so on.

    You can also save some space by pushing to the min stack only when the minimum element changes, iff the items are known to be distinct.

    0 讨论(0)
  • 2020-11-29 18:32

    The best thing exists is: Insert in O(1) Delete in O(logn) Max/Min in O(1)

    But to do that the insert function must create a link chain and you will also need an extra thread. The good news is that this link chain function also works in O(1) so it will not change the O(1) of insert.

    Delete function doesnt break the link chain.

    If the target of your delete is the max or min then the delete will be executed in O(1)

    The data structure is a mix of an avl tree and a linked list.

    The nature of a true delete is such that you cannot make it work in O(1). Hash tables which work with O(1) delete dont have the cabability to hold all the inputs.

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