数据结构红黑树题

(Application of Data Structure) A sequence of numbers are to be instered to your data structure. Whenever a number is inserted, you will be asked to report the maximum gap between two consecutive numbers in their sorted order. For example, 

output: /

1 22

output: 21

1 22 15 

output: 14 (because the sorterd oeder is 1 15 22, and 15-1 = 14 > 7 = 22-15)

1 22 15 5

ourput: 10

1 22 15 5 18

output: 10

1 22 15 5 18 9

output: 10

Show how to report the maximum hap in O(log n) time per insertion.

Solution:

解题思路:能保证所有操作都是O(log n)的数据结构是红黑树。所以先把数字插入到红黑树中,这一步用时O(log n)。插入数字后,可以计算被插入元素到successor和predecessor(和这个元素相邻的稍大一点和稍小一点的元素),这一步用时O(h)=O(log n), h是树的高度。计算与successor和predecessor的差值(gap)。每插入一个新元素时,最多有一个之前存在的gap被删除,与此同时并且产生两个新的gap。例如:1 22 gap:21 -> 1 15 22 gap:删除21 产生14 7

每次插入新元素前,我们还要记录下之前所有的gap,并且用gap组建一个新的红黑树。我们已经知道,每次插入新元素,最多会删除一个gap并产生两个新gap,所以在用gap组建的红黑树中,我们要进行三次操作:删除老gap,两次插入新gap。这一步用时3O(log n)。最后,找到gap组建的红黑树中的最大值,用时O(log n).

总用时O(log n)。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值