Arrays 两排序数组中的第k个最小元素-O(logn)解
以上是面试问题之一。有一篇关于0(logn)算法的文章解释了不变量(i+j=k–1)。我很难理解这个算法。有人能简单地解释一下这个算法吗?他们为什么把i计算成(int)((double)m/(m+n)*(k-1))。我感谢你的帮助。谢谢Arrays 两排序数组中的第k个最小元素-O(logn)解,arrays,algorithm,array-merge,Arrays,Algorithm,Array Merge,以上是面试问题之一。有一篇关于0(logn)算法的文章解释了不变量(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) { //Err
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);
受保护的静态int-kthSmallestEasy(int[]A,int-aLow,int-aLength,int[]B,int-bLow,int-bLength,int-k)
{
//错误处理
断言(aLow>=0);断言(bLow>=0);
断言(aLength>=0);断言(bLength>=0);断言(aLength+bLength>=k);
INTI=(int)((双)((k-1)*aLength/(aLength+bLength));
int j=k-1-i;
intai_1=aLow+i==0?Int32.MinValue:A[aLow+i-1];
intai=aLow+i==A.Length?Int32.MaxValue:A[aLow+i];
intbj_1=bLow+j==0?Int32.MinValue:B[bLow+j-1];
intbj=bLow+j==B.长度?Int32.MaxValue:B[bLow+j];
if(Bj_1
谁能用简单的方式解释一下这个算法呢
是的,它本质上是一种二分法
在连续的过程中,它向上移动一个数组索引上的探针,向下移动另一个索引数组上的探针,以寻求相等的值,同时保持两个索引之和等于k
还有为什么他们计算i为(int)((double)m/(m+n)*(k-1))。
假设已知点之间的值分布相等,则给出新中间点的估计值