【问题标题】:Algorithm : Median of two sorted array of different sizes算法:两个不同大小的排序数组的中位数
【发布时间】:2014-02-16 11:26:31
【问题描述】:

这是从here粘贴的代码

我无法理解它在做什么。我可以想到一个简单的算法来在合并时找到两个排序数组的中位数。这个想法是比较两个数组的中位数(m1,m2),如果m1 < m2 找到从 m1 开始的右第一个子数组和左第二个子数组到 m2 的中位数。以下代码在同一行中执行此操作,但我无法完全理解。

double findMedian(int A[], int B[], int l, int r, int nA, int nB) {
    if (l>r)
        return findMedian(B, A, max(0, (nA+nB)/2-nA), min(nB, (nA+nB)/2), nB, nA); //What does the min/max do here
    int i = (l+r)/2;
    int j = (nA+nB)/2 – i – 1;
    if (j>=0 && A[i] < B[j])
        return findMedian(A, B, i+1, r, nA, nB);
    else if (j<nB-1 && A[i] > B[j+1])
        return findMedian(A, B, l, i-1, nA, nB);
    else {
        if ( (nA+nB)%2 == 1 ) return A[i];
        else if (i>0) return (A[i]+max(B[j], A[i-1]))/2.0; //I couldn't understand this
        else return (A[i]+B[j])/2.0;
    }
}

double findMedianSortedArrays(int A[], int n, int B[], int m) {
    if (n<m)
        return findMedian(A, B, 0, n-1, n, m);
    else
        return findMedian(B, A, 0, m-1, m, n);
}

代码的第二行是做什么的?除此之外,我无法理解最后一个 else 块将如何返回中位数。当n + m 为奇数时,i 索引是否包含中位数?

感谢任何帮助、链接或指针。

【问题讨论】:

  • 也许你应该问问写这部分代码的人?
  • 如果 A={1;1} B={0;0;6;6} 算法返回 3.5 但正确答案是 1。如果 A={1;1} B={0 ;6} 缓冲区溢出。
  • 这是一个来自 leetcode 的问题(这里是link)。正如@Mr K 所提到的,您提供的算法不会给出正确的结果。为什么要费心去理解它呢?

标签: arrays algorithm median


【解决方案1】:

这是你想要做的伪代码。
我假设ar1ar2 是输入数组,两者的大小都是n

算法:

1) Calculate the medians m1 and m2 of the input arrays ar1[] 
   and ar2[] respectively.  
2) If m1 and m2 both are equal then we are done.
     return m1 (or m2)  
3) If m1 is greater than m2, then median is present in one 
   of the below two subarrays.  
    a)  From first element of ar1 to m1 (ar1[0...|_n/2_|])  
    b)  From m2 to last element of ar2  (ar2[|_n/2_|...n-1])  
4) If m2 is greater than m1, then median is present in one      
   of the below two subarrays.  
   a)  From m1 to last element of ar1  (ar1[|_n/2_|...n-1])  
   b)  From first element of ar2 to m2 (ar2[0...|_n/2_|])  
5) Repeat the above process until size of both the subarrays 
   becomes 2.  
6) If size of the two arrays is 2 then use below formula to get   
  the median.  
    Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2    

现在,您可以将其编码为您选择的任何语言。

希望这会有所帮助!

【讨论】:

  • 如何选择子数组,您将在步骤 3 和 4 中寻找中位数?如果步骤 6 中子数组的大小为 1,计算量是多少?
  • 那么中位数将是 (ar1[0], ar2[0])/2
  • 如果两个数组的大小不同怎么办?
  • @tonymiao 上述解决方案仅适用于相同大小的数组。对于大小不等的数组,必须修改算法,因为我们无法将它们分成相等的两半,因此在终止步骤中,我们不能只假设只有 2 个元素/相等的元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 2018-06-28
  • 2013-09-18
  • 1970-01-01
  • 2014-07-12
  • 2016-09-02
相关资源
最近更新 更多