【问题标题】:Median of two sorted arrays of equal length两个等长排序数组的中位数
【发布时间】:2018-01-16 21:01:57
【问题描述】:

我一直试图理解为什么以下算法无效。

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。这是我的想法:

如果 m1 > m2 那么 m1 大于合并数组中元素的一半,那么我们为什么要探索 ar1[0...|n/2|]?

【问题讨论】:

  • 如果m1太大而m2太小,则实际中位数不能在m1以上的ar1中,也不能在m2以下的ar2中。

标签: algorithm array-algorithms


【解决方案1】:

我们知道 m1 大于或等于 ar1 的前半部分。 m2 和 ar2 也是如此。同时我们也知道m1小于等于ar1的后半部分。

让我们考虑 m1 > m2 的情况

ar1:     [.....m1.....]
ar2:     [.....m2.....]
ar1+ar2: [.....m2..m1........]

让我们称合并数组的中位数为 m*。由于 ar1 和 ar2 的前半部分在 m1 之前。我们有 m1 => m*,这意味着在 ar1 中不需要考虑大于 m1 的值。所以我们只需要看前半部分或ar1即可。

同样,由于 ar1 和 ar2 的后半部分在 m1 之后,我们有 m2

这正是第 3 步和第 4 步所做的。

【讨论】:

    【解决方案2】:

    看看下面的例子。它演示了您所询问的案例。

    ar1[] = {6, 7, 8, 9, 10}
    ar2[] = {1, 2, 3, 4, 5}
    

    如果 m1 > m2 那么 m1 大于合并数组中元素的一半,那么我们为什么要探索 ar1[0...|n/2|]?

    了解此算法的关键是查看您在每一步中消除的内容,而不仅仅是您保留的内容。确实,从m1 > m2 开始,我们就知道m1 大于合并数组中一半的元素。它并没有告诉我们与合并中位数 m1 相关的位置。关于ar1 和合并中位数之间的关系,我们真正知道的是,我们可以从ar2 中消除大于m1(和小于m2)的所有内容。合并列表的中位数在剩余的某处。

    ar1[] = {6, 7, 8}
    ar2[] = {3, 4, 5}
    

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 2018-06-28
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多