Data structure that allows accessing elements by index and delete them in O(1)

前端 未结 4 1546
眼角桃花
眼角桃花 2021-01-05 15:40

I have following task (as part of bigger task):

I need to take an k element from array like data structure and delete it (k is any possible index). Arra

4条回答
  •  梦谈多话
    2021-01-05 16:08

    There is a solution, that may be satisfying in some cases. You have to use an array and a vector for saving deletions. Every time you delete an element, you put its index in a vector. Every time you read an element of some index, you recalculate its index depending on previous deletions.

    Say, you have an array of:

    A = [3, 7, 6, 4, 3]
    

    You delete 3-rd element:

    A = [3, 7, 6, 4, 3] (no actual deletion)
    d = [3]
    

    And then read the 4-th:

    i = 4
    3 < 4 => i += 1
    A[i] = 3
    

    This is not exactly O(1), but yet it does not depend on array length. Only on a number of deleted elements.

提交回复
热议问题