【发布时间】:2015-04-20 01:47:17
【问题描述】:
我正在练习与一家大型在线零售商的面试,现在正试图为“两个排序数组的中位数”问题提出一个优雅的解决方案。我知道youtube 上提出的解决方案,但我正在尝试编写一个替代方案。我已经写出来了
include <stdio.h>
int M2SA ( int * A, int m, int * B, int n )
{
/* Returns the median of two sorted arrays A and B of lengths m and n respectively.
Assumes A and B aren't both empty.
*/
int ida = 0, idb = 0, idmed = (m+n)/2;
while ((ida + idb) != idmed)
{
if (A[ida] < B[idb])
++ida;
else
++idb;
}
return (A[ida] < A[idb] ? A[ida] : B[idb]);
}
int main()
{
int arr1 [] = {1, 1, 59, 69};
int arr2 [] = {-4, 0, 49, 59, 59, 59};
printf("%d", M2SA(arr1, sizeof(arr1)/sizeof(int), arr2, sizeof(arr2)/sizeof(int)));
return 0;
}
打印出正确答案 (59),但我意识到存在一个缺陷,即我的算法仅在 idmed 不大于 m 或 n 时才有效。例如,如果数组是{1} 和{69, 293, 393, 1923129},则ida 在while 循环的第一次迭代之后等于1,因此while 循环的第二次迭代尝试访问A[1] .但是,我想不出一个简单的修复方法来添加到我的代码中。有没有简单的?
【问题讨论】:
-
中位数的一个也被广泛使用的定义(对于偶数长度系列)是将中位数周围的两个相邻数字的算术平均值作为结果。
median [1;2;3;4] = (2+3)/2 = 2.5 -
您实际上是在采用merge sort 方法来解决问题,即 O(n)。因此,您必须像处理合并排序一样处理列表结尾条件。