Find the top k sums of two sorted arrays

Given two arrays sorted in ascending order, we want to find the kth largest sum such that one element is picked from 1st array and the second element is picked from the 2nd array. I am looking for a solution involving either a min heap or a max heap.

That can be easily done in O(k). I'll only assume arrays are sorted in descending order, to simplify notation.

The idea is simple. We'll find 1st, 2nd, .., k-th maximum values one by one. But to even consider pair(i, j) we need to have both (i-1, j) and (i, j-1) already selected, because they both are greater or equal than (i, j).

It's much like if we push all n*m pairs into the heap and then remove max k times. Only we don't need all n*m pairs.

heap.add(pair(0, 0));  // biggest pair

// remove max k-1 times
for (int i = 0; i < k - 1; ++i) {
    // get max and remove it from the heap
    max = heap.popMax();

    // add next candidates
    heap.add(pair(max.i + 1, max.j));
    heap.add(pair(max.i, max.j + 1));
}

// get k-th maximum element
max = heap.popMax();
maxVal = a[max.i] + b[max.j];

Some things to consider.

  • Duplicated pairs can be added to the heap, this can be prevented with hash.
  • Indexes need to be validated, e.g. that max.i + 1 < a.length.

_______________________________________________________________________

This can be done in O(klogk) using a max-heap.

1.Start from the first two elements of the sorted arrays.Store their sum and the corresponding index into from the arrays in the heap i.e first element of the heap will contain (A[0]+B[0], 0-->index in array A,0-->index in array B)

2.We need to do Extract_Max operation k times and we need to insert two elements at each step.So there'll be at max 2*k insertions and each step we'll insert two elements based on the element extracted.
Suppose for the node extracted...i--->index in array A and j--->index in array B.
Then we'll insert A[i + 1][j] and A[i][j + 1] in the heap.

So the complexity will be O(klogk).

sorry we need to insert (A[i] + B[j+1],i,j+1) and (A[i+1]+B[j],i+1,j) instead of A[i][j+1] and A[i+1][j].

 这里有如何实现max heap的代码:http://blog.csdn.net/jiyanfeng1/article/details/41404243

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值