两个有序数组 求中位数
无病呻吟2 2008-04-07 12:41:37 有两个已排好序(从小到大)的数组A和B,长度均为n,把它们合并为一个数组,要求时间代价为O(logn),请给出算法。
下面是我在网上找到的:
Say the two arrays are sorted and increasing, namely A and B.
It is easy to find the median of each array in O(1) time.
Assume the median of array A is m and the median of array B is n.
Then,
1' If m=n, then clearly the median after merging is also m, the algorithm holds.
2' If m<n, then reserve the half of sequence A in which all numbers are greater than
m, also reserve the half of sequence B in which all numbers are smaller than n.
Run the algorithm on the two new arrays.
3' If m>n, then reserve the half of sequence A in which all numbers are smaller than
m, also reserve the half of sequence B in which all numbers are larger than n.
Run the algorithm on the two new arrays.
Time complexity: O(logn)
问题:
1.我不懂,程序什么时候退出?如果m和n永远不相等,怎么办!
2.第二和第三步里保留大于m和n的数字,那两个子数组的中位数都要去掉吗?我觉得两者的大者有可能是整个数组的中位数呀!