kth sum of two sorted arrays

转自:http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs;action=display;num=1132204952;start=50

 

一个解法可以是

q : priority queue (decreasing) := empty priority queue
add (0, 0) to q with priority a[0] + b[0]
while k > 0:
    k--
    x := pop q
    output x
    (i, j) : tuple of int,int := position of x
    if i < m:
        add (i + 1, j) to q with priority a[i + 1] + b[j]
    if j < n:
        add (i, j + 1) to q with priority a[i] + b[j + 1]
 
 
  1. The loop is executed k times.
    1. There is one pop operation per iteration.
    2. There are up to two insert operations per iteration.
  2. The maximum size of the priority queue is O(min(m, n)) O(m + n).
  3. The priority queue can be implemented with a binary heap giving log(size) pop and insert.
  4. Therefore this algorithm is O(k * log(min(m, n))) O(k * log(m + n)).
但注意可能有重复的值被添加,所以在填入q中时要先判断是否已存在,出队时删除其存在。用一个set可以方便的判断。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值