两个排序数组中的第k个最小元素 - O(log n)解

时间:2014-05-06 05:43:18

标签: arrays algorithm array-merge

以上是面试问题之一。有一篇关于0(log n)算法的文章解释了不变量(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);

1 个答案:

答案 0 :(得分:1)

Could anyone explain this algorithm in simple way

是的,它本质上是一个二分算法。

在连续传递中,它将一个数组索引上的探测向上移动而另一个索引数组向下移动,寻求相等的值,同时保持两个索引的总和等于 k

and also why do they calculate i as (int)((double)m / (m+n) * (k-1)).

假设已知点之间的值相等分布,则给出新的中间点的估计值。

相关问题