【发布时间】:2014-11-02 06:59:32
【问题描述】:
说明:
给定两个有序数组(非降序),求 T = O(lg(m + n)) 中的第 K 个最小元素,m 和 n 的长度为 2 数组,分别。
问题:
不明白下面的算法大概三点:
- 当 A[aPartitionIndex]
- 为什么不能把 A 的左边部分和 B 的右边部分放在 同一时间?
- 一些“资源”说这个算法可以应用于寻找第 Kth min 在N个排序数组中,如何?把 k 分成 N 份?
代码: Java。 解决方案:二分查找。
// k is based on 1, not 0.
public int findKthMin(int[] A, int as, int ae,
int[] B, int bs, int be, int k) {
int aLen = ae - as + 1;
int bLen = be - bs + 1;
// Guarantee the first array's size is smaller than the second one,
// which is convenient to remaining part calculation.
if (aLen > bLen) return findKthMin(B, bs, be,
A, as, ae, k);
// Base case.
if (aLen == 0) return B[bs + k - 1];
if (k == 1) return Math.min(A[as], B[bs]); // k based on 1, not 0.
// Split k,
// one part is distributed to A,
// the other part is distributed to B.
int ak = aLen < (k/2)? aLen: k/2;
int bk = k - ak;
// *k is based on 1, not 0.
int aPartitionIndex = as + (ak - 1);
int bPartitionIndex = bs + (bk - 1);
if (A[aPartitionIndex] == B[bPartitionIndex]) {
return A[aPartitionIndex];
} else if (A[aPartitionIndex] < B[bPartitionIndex]) {
// Drop the left part of A, and
// do recursion on the right part of A, and
// the entire current part of B.
k = k - ak;
return findKthMin(A, aPartitionIndex + 1, ae,
B, bs, be, k);
} else {
// Drop the left part of B, and
// do recursion on the entire current part of A, and
// the right part of B.
k = k - bk;
return findKthMin(A, as, ae,
B, bPartitionIndex + 1, be, k);
}
}
【问题讨论】:
标签: java arrays algorithm big-o divide-and-conquer