两个有序数组中查找中位数
(2014-04-23 22:08:25)
标签:
中位数查找 |
分类: 杂谈 |
原文:Median of two sorted arrays
题目:两个有序数组A和B,大小都是n,寻找这两个数组合并后的中位数。时间复杂度为O(logn)。
中位数:如果数组有个数是奇数,那么中数的值就是有序时处于中间的数;如果数组个数是偶数的,那么就是有序时中间两个数的平均值。
方法一:合并时计数
使用Merge
Sort时的Merge操作,比较两个数组时候计数,当计数达到n时,就可以得到中位数,在归并的数组中,中位数为下标n-1和n的两个数的平均值。
时间复杂度O(n)。
#include
//
- This
function returns median of ar1[] and ar2[]. - Assumptions
in this function: - Both
ar1[] and ar2[] are sorted arrays - Both
have n elements//
int getMedian(int ar1[], int ar2[], int n)
{
-
Since there are 2n elements, median will be average of elements at index n-1 and n -
in the array obtained after merging ar1 and ar2