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可以方便的判断。

 

你可能感兴趣的:(kth sum of two sorted arrays)