[回复]
[修改] [删除]
[返回版面]
|
1 |
作者: admin, 讨论版: 算法集锦, 发表时间: 2014-03-26 00:54:42 PST
标题: Max K Cross Pairs
关键字:
X和Y都是从大到小排好序的一维数组,数都是正数,数组size分别是m和n。他们一共可以组成m*n 个数对。求前K个和最大的数对。
解法:
heap.add(pair(0, 0)); // largest 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.
时间复杂度: O(klog(k))
空间复杂度: O(k)
参考资料:
[1] http://stackoverflow.com/questions/5212037/find-the-pair-across-2-arrays-with-kth-largest-sum
--
※ 来源: homecox.com [来自: 66.]
|
|
|