How to design a data structure that allows one to search, insert and delete an integer X in O(1) time

后端 未结 4 897
清歌不尽
清歌不尽 2020-12-24 14:26

Here is an exercise (3-15) in the book \"Algorithm Design Manual\".

Design a data structure that allows one to search, insert, and delete an integer X

4条回答
  •  离开以前
    2020-12-24 15:22

    Here is an idea:

    treat the array B[1..m] as a stack, and make a pointer p to point to the top of the stack (let p = 0 to indicate that no elements have been inserted into the data structure). Now, to insert an integer X, use the following procedure:

    p++;
    A[X] = p;
    B[p] = X;
    

    Searching should be pretty easy to see here (let X' be the integer you want to search for, then just check that 1 <= A[X'] <= p, and that B[A[X']] == X'). Deleting is trickier, but still constant time. The idea is to search for the element to confirm that it is there, then move something into its spot in B (a good choice is B[p]). Then update A to reflect the pointer value of the replacement element and pop off the top of the stack (e.g. set B[p] = -1 and decrement p).

提交回复
热议问题