【问题标题】:kth smallest element in two sorted array - O(log n) Solution两个排序数组中的第 k 个最小元素 - O(log n)
【发布时间】:2014-05-06 05:43:17
【问题描述】:

以上是面试题之一。有一篇关于 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);

【问题讨论】:

    标签: arrays algorithm array-merge


    【解决方案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)).

    这给出了新的中间点的估计值,假设已知点之间的值是均匀分布的。

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 2017-03-04
      • 1970-01-01
      • 2018-06-30
      • 2016-03-20
      • 1970-01-01
      • 2010-09-20
      相关资源
      最近更新 更多