以上是面试问题中的一个。有一篇关于0(log )算法的文章解释了不变量(i +j=k- 1)。我很难理解这个算法。有人能用简单的方式解释这个算法吗?为什么他们计算i为(int)((double)m / (m+n) * (k-1))。我很感谢你的帮助。谢谢。
protected static int kthSmallestEasy(int[] A, int aLow, int aLength, int[] B, int bLow, int bLength, int k)
{
//Error Handling
assert(aLow >= 0); assert(bLow >= 0);
assert(aLength >= 0); assert(bLength >= 0); assert(aLength + bLength >= k);
int i = (int)((double)((k - 1) * aLength / (aLength + bLength)));
int j = k - 1 - i;
int Ai_1 = aLow + i == 0 ? Int32.MinValue : A[aLow + i - 1];
int Ai = aLow + i == A.Length ? Int32.MaxValue : A[aLow + i];
int Bj_1 = bLow + j == 0 ? Int32.MinValue : B[bLow + j - 1];
int Bj = bLow + j == B.Length ? Int32.MaxValue : B[bLow + j];
if (Bj_1 < Ai && Ai < Bj)
return Ai;
else if (Ai_1 < Bj && Bj < Ai)
return Bj;
assert(Ai < Bj - 1 || Bj < Ai_1);
if (Ai < Bj_1) // exclude A[aLow .. i] and A[j..bHigh], k was replaced by k - i - 1
return kthSmallestEasy(A, aLow + i + 1, aLength - i - 1, B, bLow, j, k - i - 1);
else // exclude A[i, aHigh] and B[bLow .. j], k was replaced by k - j - 1
return kthSmallestEasy(A, aLow, i, B, bLow + j + 1, bLength - j - 1, k - j - 1);
发布于 2014-05-06 13:58:53
Could anyone explain this algorithm in simple way
。
是的,它本质上是一个二等分算法。
在连续的遍历中,它向上移动一个数组索引上的探针,向下移动另一个索引数组上的探针,寻求相等的值,同时保持两个索引的总和等于k。
and also why do they calculate i as (int)((double)m / (m+n) * (k-1)).
这给出了一个新的中点的估计,假设值在已知点之间均匀分布。
https://stackoverflow.com/questions/23486757
复制相似问题