TADM_3-15

Problem:

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

X in O(1) time (i.e. , constant time, independent of the total number of integers
stored). Assume that 1 ≤ X ≤ n and that there are m+n units of space available,
where m is the maximum number of integers that can be in the table at any one
time. (Hint: use two arrays A[1..n] and B[1..m].) You are not allowed to initialize
either A or B, as that would take O(m) or O(n) operations. This means the arrays

are full of random garbage to begin with, so you must be very careful.


Solution:

With an additional variable recording the size of the container.

To insert x, search x first

    if size==m, return;

    if x exists, return.

    if x not exists, set A[x] = size, B[size]=x, size++,;

To search x

    if A[x] > size, return false;

    if B[A[x]] == x, return true;

To delete x

    if A[x] > size, return false;

    if B[A[x]] == x, A[x] = -1, B[A[x]]=-1;


Fallbacks:

    For the above implementation, the container can only insert m times. If someone delete and inserts again when the container is full, it won't accept that value.

    To reuse the wholes in B, we have to iterate m to look for holes, resulting in a O(m) time.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值